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?

30分かけてわかるAzure Functions App (Pythonを動かすサンプルコード&Terraformコード&構築手順付属)

0
Last updated at Posted at 2026-09-04

👀概要

Azureのサーバーレス実行環境である「Azure Functions App」を、AWS Lambdaと比較しながら整理します。
さらに、現在推奨される構成である Flex Consumption をTerraformで構築する方法や主要な引数の意味、Pythonコードのリリース手順までを解説します。

※比較表は2026年9月2日時点、Terraformのリソース仕様は2026年4月時点のAzureRMプロバイダーに基づいています。

👨‍👩‍👧‍👦対象者(Who)

  • Azureを初めて触る方(特にAWS経験者)
  • インフラエンジニア、クラウドエンジニア

📌関連リンク

🗒️目次

  • Azure Functions Appとは
    • AWS Lambdaとの比較表
    • ホスティングプラン
  • TerraformでFlex Consumptionを構築してみる
    • IaCの準備と実行
  • Pythonコードの準備とリリース
  • まとめ

📝 内容

Azure Functions Appとは

Azure Functions Appとはサーバーレスな実行環境を提供するAzureのサービスです。
サーバーのデプロイを実施することなく、コードを実行することができます。

AWSでのLambdaに該当します。

AWS Lambdaとの比較表

以下AWS LambdaとAzure Functions Appの比較表を作成しました。(2026年9月2日時点)
Azure Functions Appはスペック周りがプランによって大きく異なります。

項目 Azure Functions App AWS Lambda
実行モデル サーバーレス サーバーレス
料金体系 実行時間とメモリに基づく従量課金 実行時間とメモリに基づく従量課金
サポート言語 C#, .NET, Java, JavaScript, Python, PowerShell, TypeScript, Go .NET, Node.js, Python, Ruby, Java, Go
最大実行時間 プランによって異なる。 15分
メモリ プランによって異なる。 128MB~10GB
トリガー HTTPトリガー、Queue、Blob、Event Grid等 API Gateway、S3、DynamoDB、EventBridge、SQS等
デプロイ方法 Azure Portal、CLI、VS Code、CI/CD 等々 AWS Console、CLI、SAM、Serverless Framework 等々

ホスティングプラン

Azure Functions Appのスペックや料金は、どのホスティングプランを選ぶかで大きく変わります。

  1. Consumption plan(レガシーな従量課金プラン)
    • 従来からある自動スケーリングのプランだが、レガシーかつ非推奨
    • 実行時のみ課金
    • コールドスタート
  2. Flex Consumption plan
    • 従量課金でありつつ、VNet統合とスケーリング制御が可能
    • always_ready により、コールドスタートを緩和できる
    • Consumption planではなく、こちらのFlex Consumption planを使用することが推奨されます。
  3. Premium plan
    • 常時稼働インスタンス。常にウォーム状態を選択可能。
    • より大きなインスタンスサイズ

他にも専用プラン/コンテナアプリプラン等があります。

参考 : Azure Functions App ホスティング オプション

TerraformでFlex Consumptionを構築してみる

IaCの準備と実行

以下は azurerm_function_app_flex_consumption を使用したサンプルコードです。

以下のコードをmain.tfという名前で保存した後、 terraform init terraform apply を順に実行してみてください。
もちろんAzureへの接続ができていることが前提条件にあるため、az login 等のコマンドで疎通確認をしておく必要があります。

# 1. 変数定義(再利用性と保守性の向上)
variable "project_name" {
  default = "testminegishi"
}

variable "location" {
  default = "japaneast" # お好みのリージョンに
}

provider "azurerm" {
  features {}
}

# 2. リソースグループ
resource "azurerm_resource_group" "example" {
  name     = "rg-${var.project_name}"
  location = var.location
}

# 3. ストレージアカウント
# 名前は一意である必要があるため、ランダム文字列を付与するのが一般的です
resource "azurerm_storage_account" "example" {
  name                     = "st${var.project_name}"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_container" "example" {
  name                  = "app-package"
  storage_account_id    = azurerm_storage_account.example.id
  container_access_type = "private"
}

# 4. Flex Consumption 用のサービスプラン
resource "azurerm_service_plan" "example" {
  name                = "asp-${var.project_name}"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  sku_name            = "FC1"
  os_type             = "Linux"
}

# 5. Flex Consumption Function App
resource "azurerm_function_app_flex_consumption" "example" {
  name                = "func-app-${var.project_name}"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  service_plan_id     = azurerm_service_plan.example.id

  runtime_name           = "python"
  runtime_version        = "3.12"
  maximum_instance_count = 50
  instance_memory_in_mb  = 2048

  storage_container_type     = "blobContainer"
  storage_container_endpoint = "https://${azurerm_storage_account.example.name}.blob.core.windows.net/${azurerm_storage_container.example.name}"
  storage_authentication_type = "StorageAccountConnectionString"
  storage_access_key          = azurerm_storage_account.example.primary_access_key

  app_settings = {
    "AzureWebJobsStorage" = "DefaultEndpointsProtocol=https;AccountName=${azurerm_storage_account.example.name};AccountKey=${azurerm_storage_account.example.primary_access_key};EndpointSuffix=core.windows.net"
  }

  site_config {
    app_command_line = ""
  }

  identity {
    type = "SystemAssigned"
  }
}

# 6. アウトプット(作成後にURLなどをすぐ確認できる)
output "function_app_name" {
  value = azurerm_function_app_flex_consumption.example.name
}

output "function_app_default_hostname" {
  value = azurerm_function_app_flex_consumption.example.default_hostname
}

Flex Consumptionは azurerm_service_plan のSKUに FC1 を指定することで利用可能になります。
このFCはFlex Consumptionの略です。

Note: azurerm_function_app_flex_consumptionazurerm_linux_function_app の違い

azurerm_function_app_flex_consumption は新しい実行形態「Flex Consumption」専用のリソースです。従量課金でありつつ、ネットワーク性能・スケーリングの制御が可能です。「Flex Consumption が次世代の標準」という立ち位置のため、Linux環境でAzure Functions Appを構築する際は基本的にこちらを使用してください。

Flex Consumptionについての引数は以下の通りです。

  • 基本設定
    • name : Azure Functions App の名前。
    • resource_group_name : Azure Functions Appを配置するリソースグループ名。
    • location : リージョン。日本ならばjapaneast
    • runtime_name : 使用する言語。 node, dotnet-isolated, powershell, python, java から選択。
    • runtime_version : ランタイムのバージョン。使用する言語のバージョン指定をここで行います。
    • storage_container_type : ストレージの種類。現在サポートされている値は blobContainer のみです。関数の実行コードが保管されます。
  • パフォーマンスに関する設定
    • maximum_instance_count : 最大インスタンス数。1〜1000の間で設定可能。
    • always_ready : 常に稼働させておくインスタンス数を指定できます。
  • ネットワークに関する設定
    • virtual_network_subnet_id : VNet内でのデプロイを行う際のオプションで、サブネットを指定することでその中に配置されます。ただし、このサブネット内への配置は必須ではありません。
    • https_only : httpsのみの接続を許可します。
    • public_network_access_enabled : パブリックネットワークからのアクセスを許可するかどうかです。デフォルトは許可。
  • Azure Functions App 公開設定 site_config ブロックには Function App を公開するための設定が記載されます。
    • IP制限 ip_restriction
      • 設定例1 : 特定のIPアドレス(例: 会社のオフィスなど)のみ許可
      ip_restriction {
          ip_address  = "203.0.113.10/32"
          action      = "Allow"
          priority    = 100
          name        = "AllowOfficeIP"
          description = "Allow access from office"
      }
      
      • 設定例2 : 特定のサブネット(VNet)からのアクセスを許可
      ip_restriction {
          virtual_network_subnet_id = azurerm_subnet.example.id
          action                    = "Allow"
          priority                  = 200
          name                      = "AllowVNetSubnet"
      }
      
    • 設定時のポイント
      • 優先順位 (priority) : 数字が小さいほど優先されます。
      • アクション (action) : Allow(許可)または Deny(拒否)を指定します。
    • public_network_access_enabled = false を設定している場合は、上記のIP制限は意味をなしません。

実行後

上記のコードを実行することで、5つのリソースが新規に出来上がります。

以下実行結果サンプルです。

ec2-user in 🌐 ip-172-16-12-188 in ~/environment/main via 💠 default took 1m54s 
❯ terraform apply

...中略

azurerm_resource_group.example: Creating...
azurerm_resource_group.example: Still creating... [00m10s elapsed]
azurerm_resource_group.example: Still creating... [00m20s elapsed]
azurerm_resource_group.example: Creation complete after 26s [id=/subscriptions/xxxx-xxxx-xxxxxxxxxxxxxx-xxxxxxxxxx/resourceGroups/rg-testminegishi]
azurerm_service_plan.example: Creating...
azurerm_storage_account.example: Creating...
azurerm_service_plan.example: Still creating... [00m10s elapsed]
azurerm_storage_account.example: Still creating... [00m10s elapsed]
azurerm_service_plan.example: Creation complete after 14s [id=/subscriptions/xxxx-xxxx-xxxxxxxxxxxxxx-xxxxxxxxxx/resourceGroups/rg-testminegishi/providers/Microsoft.Web/serverFarms/asp-testminegishi]
azurerm_storage_account.example: Still creating... [00m20s elapsed]
azurerm_storage_account.example: Creation complete after 23s [id=/subscriptions/xxxx-xxxx-xxxxxxxxxxxxxx-xxxxxxxxxx/resourceGroups/rg-testminegishi/providers/Microsoft.Storage/storageAccounts/sttestminegishi]
azurerm_storage_container.example: Creating...
azurerm_storage_container.example: Still creating... [00m10s elapsed]
azurerm_storage_container.example: Creation complete after 11s [id=/subscriptions/xxxx-xxxx-xxxxxxxxxxxxxx-xxxxxxxxxx/resourceGroups/rg-testminegishi/providers/Microsoft.Storage/storageAccounts/sttestminegishi/blobServices/default/containers/app-package]
azurerm_function_app_flex_consumption.example: Creating...
azurerm_function_app_flex_consumption.example: Still creating... [00m10s elapsed
azurerm_function_app_flex_consumption.example: Creation complete after 48s [id=/subscriptions/xxxx-xxxx-xxxxxxxxxxxxxx-xxxxxxxxxx/resourceGroups/rg-testminegishi/providers/Microsoft.Web/sites/func-app-testminegishi]

Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

Outputs:

function_app_default_hostname = "func-app-testminegishi.azurewebsites.net"
function_app_name = "func-app-testminegishi"

正常に実行が完了すると、以下のようにリソースが作成されます。

  • リソースグループ

image.png

  • Azure Functions App

image.png

  • ストレージアカウント

image.png

  • App Service プラン

image.png

Pythonコードの準備とリリース

Azure Functions Appの中で動かすコードは以下の通りです。
シンプルなAPIをエンドポイント v1/test に用意しました。

import azure.functions as func
import json
import logging

app = func.FunctionApp()

@app.route(route="v1/test", methods=["GET"], auth_level=func.AuthLevel.FUNCTION)
def db_test(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('データベース接続テストAPI - リクエスト受信')

    try:
        return func.HttpResponse(
            json.dumps({
                "status": "success",
                "message": "hello world",
            }, ensure_ascii=False, default=str),
            status_code=200,
            mimetype="application/json"
        )
    except Exception as e:
        logging.error(f"データベース接続エラー: {str(e)}")
        return func.HttpResponse(
            json.dumps({"status": "error", "message": f"データベース接続失敗: {str(e)}"}),
            status_code=500,
            mimetype="application/json"
        )

このコードと以下の host.json/requirements.txt をフォルダー v1 配下に保存します。

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}
  • requirements.txt は以下の通りです。 Azure Functions Appのためのライブラリのみを必要とします。
azure-functions
  • リリース実行環境としてはDockerコンテナを使用しました。azure-functions-core-tools を使用する必要があるのですが、このツールの開発環境へのインストールもうまくいかなかったため、Dockerコンテナ内でリリースコマンドを実行します。
FROM debian:bookworm

# Set non-interactive frontend to avoid tzdata prompts, etc.
ENV DEBIAN_FRONTEND=noninteractive
ENV DEBIAN_VERSION=12


# Install prerequisites and add Microsoft package source for Azure Functions Core Tools
RUN apt-get update && \
    apt-get install -y --no-install-recommends gpg wget ca-certificates apt-transport-https && \
    wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | tee /usr/share/keyrings/microsoft-prod.gpg > /dev/null && \
    wget -q https://packages.microsoft.com/config/debian/$DEBIAN_VERSION/prod.list && \
    mv prod.list /etc/apt/sources.list.d/microsoft-prod.list && \
    chown root:root /usr/share/keyrings/microsoft-prod.gpg && \
    chown root:root /etc/apt/sources.list.d/microsoft-prod.list && \
    apt-get update && \
    apt-get install -y --no-install-recommends azure-functions-core-tools-4 libicu-dev && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl ca-certificates gnupg lsb-release apt-transport-https && \
    curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /usr/share/keyrings/microsoft.gpg && \
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/microsoft.gpg] https://packages.microsoft.com/repos/azure-cli/ bookworm main" > /etc/apt/sources.list.d/azure-cli.list && \
    apt-get update && \
    apt-get install -y --no-install-recommends azure-cli && \
    az --version
COPY . /code/
RUN apt-get install -y python3-pip && \
    pip install -r /code/v1/requirements.txt --break-system-packages

これらのファイルを用意できたら、以下のコマンドでリリースを実施します。

export FUNCTION_APP_NAME="func-app-testminegishi"
docker build -t azure-func-tools:latest .
docker run --rm -v ~/.azure:/root/.azure -v .:/code -it -p 8080:8080 azure-func-tools:latest bash -c "cd /code/v1; func azure functionapp publish ${FUNCTION_APP_NAME} --python --force"

リリースができると以下のように関数が確認できます。

image.png

これをクリックし、「関数のURLを取得」を押すとアクセスキーを含めたURLを取得できます。

image.png

これにアクセスすると、Hello Worldが出力されました。

ec2-user in 🌐 ip-172-16-12-188 in environment/main/code via 🐍 v3.14.7 
❯ curl https://func-app-testminegishi.azurewebsites.net/api/v1/test?code=7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
{"status": "success", "message": "hello world"}

まとめ

  • Azure Functions AppはAWS Lambdaに相当するAzureのサーバーレス実行環境です。
  • 現在は Flex Consumption plan が推奨プランであり、Terraformでは azurerm_function_app_flex_consumption リソースを使うことで構築できます。
  • Pythonコードのリリースには azure-functions-core-tools が必要ですが、開発環境へのインストールがうまくいかない場合はDockerコンテナ経由でのリリースが有効な回避策になります。
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?