0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Azure Static Web AppをBicepで自動デプロイする方法

Posted at

Azure Static Web AppをBicepで自動デプロイする方法

はじめに

Azure Static Web Apps は、モダンなWebアプリケーションを簡単にホスティングできるAzureのサービスです。GitHub Actions と組み合わせることで、コードをプッシュするだけで自動的にビルド・デプロイが実行されるCI/CDパイプラインを構築できます。

本記事では、Bicep(Azure Resource Manager テンプレートの新しい言語)を使用して、Azure Static Web App を自動デプロイする方法を詳しく解説します。PowerShellスクリプトとBicepテンプレートを組み合わせた実用的なアプローチを紹介し、そのまま実際のプロジェクトで活用できる完全なサンプルコードを提供します。

前提条件

必要なツール・モジュール

  • Azure PowerShell モジュール
  • Azure CLI または Azure PowerShell
  • Bicep CLI
  • GitHubリポジトリとPersonal Access Token

必要な権限・アクセス

  • Azure サブスクリプションの共同作成者権限
  • GitHubリポジトリへの管理者権限
  • リソースグループの作成・編集権限

前提知識

  • Bicepの基本的な文法
  • Azure Static Web Appsの概念
  • GitHub Actionsの基本知識

Static Web App用Bicepテンプレートの作成

1. Bicepテンプレートの構造設計

まず、Azure Static Web App をデプロイするためのBicepテンプレートを作成します。このテンプレートでは、セキュリティとメンテナビリティを重視した設計を行います。

// Azure Static Web Apps Bicep テンプレート
@metadata({
  author: '開発チーム'
  version: '1.0.0'
  lastUpdated: '2025-07-23'
  tags: ['staticwebapp', 'azure', 'bicep', 'IaC']
  license: 'MIT'
})

@description('作成する Static Web App のリソース名')
@minLength(3)
@maxLength(60)
param name string

@description('リソースのデプロイ先リージョン。省略時はリソースグループのリージョンを使用')
@minLength(3)
@maxLength(30)
param location string = resourceGroup().location

@description('SKU。"Free" または "Standard" を指定可能')
@allowed([
  'Free'
  'Standard'
])
param sku string = 'Free'

2. アプリケーション構成の定義

Static Web App の構成に関するパラメータを定義します。これらのパラメータは、GitHubリポジトリの構造に合わせて調整が必要です。

@description('API のルートディレクトリ')
@minLength(1)
@maxLength(100)
param apiLocation string = 'Api'

@description('アプリのルートディレクトリ')
@minLength(1)
@maxLength(100)
param appLocation string = 'Client'

@description('ビルド成果物の出力先ディレクトリ')
@minLength(1)
@maxLength(200)
param outputLocation string = 'Client/wwwroot'

@description('GitHub リポジトリの URL')
@minLength(10)
@maxLength(200)
param repositoryUrl string

@description('デプロイ対象のブランチ名')
@minLength(1)
@maxLength(100)
param branch string = 'main'

@description('GitHub Actions用のデプロイトークン')
@minLength(10)
@maxLength(200)
param repositoryToken string

重要なポイント

  • @minLength@maxLength による入力値検証
  • @description による明確なパラメータ説明
  • @allowed による選択肢の制限

3. Static Web App リソースの定義

メインとなるStatic Web Appリソースを定義します。このリソースがGitHubリポジトリと連携し、自動デプロイを実現します。

resource staticWebApp 'Microsoft.Web/staticSites@2022-09-01' = {
  name: name
  location: location
  sku: {
    name: sku
  }
  properties: {
    repositoryUrl: repositoryUrl
    branch: branch
    repositoryToken: repositoryToken
    buildProperties: {
      apiLocation: apiLocation
      appLocation: appLocation
      outputLocation: outputLocation
    }
  }
}

// デプロイ後の重要な情報を出力
output staticWebAppName string = staticWebApp.name
output staticWebAppHostname string = staticWebApp.properties.defaultHostname

技術的解説

  • Microsoft.Web/staticSites@2022-09-01:最新のAPIバージョンを使用
  • buildProperties:GitHub Actionsでのビルド設定を定義
  • output:デプロイ後に必要な情報を出力(後続の処理で活用可能)

パラメータファイルの作成

4. Bicepパラメータファイルの構成

Bicepテンプレートで使用するパラメータ値を外部ファイルで管理します。これにより、環境ごとの設定変更が容易になります。

using './staticwebapp.bicep'

param name = 'stapp-myproject-dev'
param location = 'eastasia'
param sku = 'Standard'
param apiLocation = 'Api'
param appLocation = 'Client'
param outputLocation = 'Client/wwwroot'
param repositoryUrl = 'https://github.com/your-org/your-repo'
param branch = 'main'
param repositoryToken = 'ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

セキュリティ上の注意

  • repositoryToken は機密情報のため、実際の運用では Azure Key Vault などを使用
  • パラメータファイルをGitリポジトリにコミットする場合は、機密情報を除外

PowerShellデプロイスクリプトの実装

5. 汎用的なデプロイスクリプトの作成

Bicepテンプレートを使用してAzureにデプロイするPowerShellスクリプトを作成します。このスクリプトは再利用性とエラーハンドリングを重視した設計になっています。

<#
.SYNOPSIS
    Bicepファイルを使ってAzureリソースグループへデプロイを行うスクリプト
.DESCRIPTION
    指定したBicepテンプレートとパラメータファイルを用いて、Azureリソースグループにデプロイします。
    リソースグループはフル名または末尾の番号で指定可能です。
.PARAMETER ResourceGroup
    デプロイ先のリソースグループ名、または末尾の番号。
.PARAMETER TemplateFilePath
    デプロイに使用するBicepファイルのフルパス。
.PARAMETER ParameterFilePath
    パラメータファイルのフルパス。省略時はBicepファイル名+"param"が既定値。
.EXAMPLE
    .\DeployBicep.ps1 -ResourceGroup "my-resource-group" -TemplateFilePath "C:\templates\staticwebapp.bicep"
#>

Param(
    [Parameter(Mandatory, HelpMessage = 'デプロイ先リソースグループ名')]
    [string]$ResourceGroup,

    [Parameter(Mandatory, HelpMessage = 'Bicepファイルのフルパス')]
    [string]$TemplateFilePath,

    [Parameter(HelpMessage = 'パラメータファイルのフルパス(省略可)')]
    [string]$ParameterFilePath = $TemplateFilePath + 'param'
)

6. ファイル検証とエラーハンドリング

デプロイ前に必要なファイルの存在確認と形式チェックを実装します。

try {
    # Bicepファイルの存在と拡張子チェック
    if (-not (Test-Path $TemplateFilePath)) {
        throw "指定されたBicepファイルが見つかりません: $TemplateFilePath"
    }
    
    if ([System.IO.Path]::GetExtension($TemplateFilePath) -ne '.bicep') {
        throw "Bicepファイルの拡張子が正しくありません。.bicep ファイルを指定してください。"
    }

    # パラメータファイルが指定されている場合のみチェック
    if ($ParameterFilePath -and (Test-Path $ParameterFilePath)) {
        $paramExtension = [System.IO.Path]::GetExtension($ParameterFilePath)
        if ($paramExtension -notin @('.bicepparam', '.json')) {
            throw "パラメータファイルの拡張子が正しくありません。.bicepparam または .json ファイルを指定してください。"
        }
    }

    Write-Host "✓ ファイル検証が完了しました" -ForegroundColor Green
} catch {
    Write-Error "ファイル検証でエラーが発生しました: $_"
    exit 1
}

7. Azure リソースグループへのデプロイ実行

検証が完了したら、実際にAzureへデプロイを実行します。

try {
    Write-Host "デプロイを開始します..." -ForegroundColor Yellow
    Write-Host "  リソースグループ: $ResourceGroup" -ForegroundColor Cyan
    Write-Host "  テンプレートファイル: $TemplateFilePath" -ForegroundColor Cyan
    Write-Host "  パラメータファイル: $ParameterFilePath" -ForegroundColor Cyan

    # デプロイ実行
    $deploymentResult = New-AzResourceGroupDeployment `
        -ResourceGroupName $ResourceGroup `
        -TemplateFile $TemplateFilePath `
        -TemplateParameterFile $ParameterFilePath `
        -Verbose

    if ($deploymentResult.ProvisioningState -eq 'Succeeded') {
        Write-Host "✓ デプロイが正常に完了しました" -ForegroundColor Green
        
        # デプロイ結果の出力
        if ($deploymentResult.Outputs) {
            Write-Host "`nデプロイ結果:" -ForegroundColor Yellow
            $deploymentResult.Outputs | ForEach-Object {
                Write-Host "  $($_.Key): $($_.Value.Value)" -ForegroundColor Cyan
            }
        }
    } else {
        throw "デプロイが失敗しました。状態: $($deploymentResult.ProvisioningState)"
    }

} catch {
    Write-Error "デプロイ処理でエラーが発生しました: $_"
    exit 1
}

完全なサンプルスクリプト

8. 統合されたデプロイスクリプト

以下は、実際に動作する完全なデプロイスクリプトです。

<#
.SYNOPSIS
    Azure Static Web App を Bicep を使ってデプロイするスクリプト
.DESCRIPTION
    Bicepテンプレートを使用してAzure Static Web Appをデプロイします。
    ファイル検証、エラーハンドリング、デプロイ結果の表示を含む完全なソリューションです。
.EXAMPLE
    .\DeployStaticWebApp.ps1 -ResourceGroup "rg-myapp-dev" -TemplateFilePath ".\staticwebapp.bicep"
#>

[CmdletBinding()]
Param(
    [Parameter(Mandatory)]
    [string]$ResourceGroup,

    [Parameter(Mandatory)]
    [string]$TemplateFilePath,

    [Parameter()]
    [string]$ParameterFilePath = $TemplateFilePath + 'param'
)

function Test-AzureConnection {
    try {
        $context = Get-AzContext
        if (-not $context) {
            Write-Host "Azureに接続していません。Connect-AzAccount を実行してください。" -ForegroundColor Red
            return $false
        }
        Write-Host "✓ Azure接続確認完了: $($context.Account.Id)" -ForegroundColor Green
        return $true
    } catch {
        Write-Host "Azure接続の確認でエラーが発生しました: $_" -ForegroundColor Red
        return $false
    }
}

function Test-ResourceGroupExists {
    param([string]$ResourceGroupName)
    
    try {
        $rg = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue
        if ($rg) {
            Write-Host "✓ リソースグループが見つかりました: $ResourceGroupName" -ForegroundColor Green
            return $true
        } else {
            Write-Host "警告: リソースグループが見つかりません: $ResourceGroupName" -ForegroundColor Yellow
            Write-Host "デプロイ時に自動作成されます。" -ForegroundColor Yellow
            return $false
        }
    } catch {
        Write-Host "リソースグループの確認でエラーが発生しました: $_" -ForegroundColor Red
        return $false
    }
}

# メイン処理
try {
    Write-Host "=== Azure Static Web App Bicep デプロイスクリプト ===" -ForegroundColor Magenta
    
    # Azure接続確認
    if (-not (Test-AzureConnection)) {
        exit 1
    }
    
    # ファイル存在確認
    if (-not (Test-Path $TemplateFilePath)) {
        throw "Bicepテンプレートファイルが見つかりません: $TemplateFilePath"
    }
    
    if ($ParameterFilePath -and -not (Test-Path $ParameterFilePath)) {
        throw "パラメータファイルが見つかりません: $ParameterFilePath"
    }
    
    # リソースグループ確認
    Test-ResourceGroupExists -ResourceGroupName $ResourceGroup
    
    # デプロイ実行
    Write-Host "`nデプロイを開始します..." -ForegroundColor Yellow
    
    $deploymentName = "staticwebapp-deploy-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
    
    $deploymentParams = @{
        ResourceGroupName = $ResourceGroup
        TemplateFile = $TemplateFilePath
        Name = $deploymentName
        Verbose = $true
    }
    
    if ($ParameterFilePath -and (Test-Path $ParameterFilePath)) {
        $deploymentParams.TemplateParameterFile = $ParameterFilePath
    }
    
    $result = New-AzResourceGroupDeployment @deploymentParams
    
    if ($result.ProvisioningState -eq 'Succeeded') {
        Write-Host "`n✓ デプロイが正常に完了しました!" -ForegroundColor Green
        Write-Host "デプロイ名: $deploymentName" -ForegroundColor Cyan
        
        if ($result.Outputs.Count -gt 0) {
            Write-Host "`n=== デプロイ結果 ===" -ForegroundColor Yellow
            foreach ($output in $result.Outputs.GetEnumerator()) {
                Write-Host "$($output.Key): $($output.Value.Value)" -ForegroundColor Cyan
            }
        }
    } else {
        throw "デプロイに失敗しました。状態: $($result.ProvisioningState)"
    }
    
} catch {
    Write-Error "エラーが発生しました: $_"
    exit 1
} finally {
    Write-Host "`n処理が完了しました。" -ForegroundColor Magenta
}

実行方法とポイント

技術的なメリット

Infrastructure as Code (IaC) の活用

  • Bicepを使用することで、インフラストラクチャの宣言的な定義が可能
  • バージョン管理による変更履歴の追跡
  • 環境間での一貫した構成の保証

自動化とCI/CD統合

  • GitHub Actionsとの自動連携
  • コードプッシュによる自動デプロイ
  • ブランチベースのデプロイメント戦略

セキュリティとベストプラクティス

  • パラメータ検証による入力値の安全性確保
  • エラーハンドリングによる予期しない動作の防止
  • 機密情報の外部化によるセキュリティ向上

活用例

開発チームでの利用

  • 開発環境、ステージング環境、本番環境の統一的な管理
  • 新機能開発時の一時的な環境構築
  • Pull Request単位での独立した検証環境の作成

CI/CDパイプラインとの統合

  • Azure DevOps Pipelinesでの自動デプロイ
  • GitHub Actionsワークフローでの活用
  • 複数環境への段階的デプロイメント

運用での応用

  • 災害復旧時の迅速な環境復元
  • 設定変更の標準化とドキュメント化
  • コスト最適化のためのリソース管理

この記事で紹介したBicepテンプレートとPowerShellスクリプトを組み合わせることで、Azure Static Web Appの効率的で安全なデプロイメントが実現できます。実際のプロジェクトでは、GitHubトークンの管理やリソース命名規則など、組織固有の要件に合わせてカスタマイズしてご活用ください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?