Linux と PostgreSQL のワークロードを探して実行する

完了

このユニットでは、次のことを行います。

  • Bicep テンプレートを使用して Azure Blob Storage アカウントをデプロイします。
  • Blob Storage コンテナーを作成する。
  • イメージを Blob Storage アカウントに移行します。
  • tailwind.sql を Blob Storage アカウントにアップロードします。
  • Azure CLI を使用して Azure 仮想マシンに接続します。
  • ストレージ アカウントからファイルをダウンロードします。
  • psql を使用して PostgreSQL サーバーに接続し、SQL ファイルをインポートします。
  • コマンド ラインを介してアプリケーションを対話的に実行します。
  • アプリケーションが正しく動作することを確認します。

deploy/vm-postgres.bicep を使用してストレージ アカウントをデプロイする

ローカル コンピューター上で次のコマンドを実行します:

az deployment group create \
    --resource-group 240900-linux-postgres \
    --template-file deploy/vm-postgres.bicep \
    --parameters \
        deployVm=false \
        deployPostgres=false \
        deployStorage=true

現在のユーザーをストレージ BLOB データ所有者ロールに追加する

STORAGE_ACCOUNT_ID=$(az storage account list \
    --resource-group 240900-linux-postgres \
    --query '[0].id' \
    -o tsv)

USER_ID=$(az ad signed-in-user show \
    --query id \
    -o tsv)

az role assignment create \
    --role "Storage Blob Data Owner" \
    --assignee $USER_ID \
    --scope $STORAGE_ACCOUNT_ID

ストレージ アカウントに container1 というコンテナーを作成する

STORAGE_ACCOUNT_NAME=$(az storage account list \
    --resource-group 240900-linux-postgres \
    --query '[0].name' \
    -o tsv)

echo "STORAGE_ACCOUNT_NAME: $STORAGE_ACCOUNT_NAME"

az storage container create \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --name container1

イメージをストレージ アカウントのサブフォルダーに移行する

az storage blob upload-batch \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --overwrite \
    --destination container1/images \
    --source app/data/images

次のような出力が表示されます。

[
  {
    "Blob": "https://storageji2dbe.blob.core.windows.net/container1/images/wrench_set.jpg",
    "Last Modified": "...",
    "Type": "image/jpeg",
    "eTag": "\"0x8DCE0CA938AF41B\""
  },
  {
    "Blob": "https://storageji2dbe.blob.core.windows.net/container1/images/planer.jpg",
    "Last Modified": "...",
    "Type": "image/jpeg",
    "eTag": "\"0x8DCE0CA939DF18B\""
  },
  ...
]

app/data/postgres/tailwind.sql をストレージ アカウントにアップロードする

az storage blob upload \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --container-name container1 \
    --file app/data/postgres/tailwind.sql \
    --name tailwind.sql

az ssh コマンドを使用して Azure 仮想マシンに接続する

az ssh vm \
    --resource-group 240900-linux-postgres \
    --name vm-1

ストレージ アカウントから tailwind.sql ファイルをダウンロードする

Bash 変数 STORAGE_ACCOUNT_NAME をストレージ アカウント名に設定します:

STORAGE_ACCOUNT_NAME=$(az storage account list \
    --resource-group 240900-linux-postgres \
    --query '[0].name' \
    -o tsv)

echo "STORAGE_ACCOUNT_NAME: $STORAGE_ACCOUNT_NAME"

tailwind.sql コマンドを使用して、az storage blob download を Azure 仮想マシンにダウンロードします:

az storage blob download \
    --account-name $STORAGE_ACCOUNT_NAME \
    --auth-mode login \
    --container-name container1 \
    --file tailwind.sql \
    --name tailwind.sql

リモート マシン上で psql の環境変数を設定する

MANAGED_IDENTITY_NAME=240900-linux-postgres-identity
export AZURE_CLIENT_ID=$(az identity show --resource-group 240900-linux-postgres --name $MANAGED_IDENTITY_NAME --query "clientId" -o tsv)
PG_NAME=$(az postgres flexible-server list --resource-group 240900-linux-postgres --query "[0].name" -o tsv)

# Set psql environment variables
export PGHOST="${PG_NAME}.privatelink.postgres.database.azure.com"
export PGPASSWORD=$(curl -s "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fossrdbms-aad.database.windows.net&client_id=${AZURE_CLIENT_ID}" -H Metadata:true | jq -r .access_token)
export PGUSER=$MANAGED_IDENTITY_NAME
export PGDATABASE=postgres

psql を使用して tailwind.sql をインポートする

psql -f tailwind.sql

Postgres サーバーに接続して、インポートが成功したことを確認する

psql

テーブルを一覧表示する

\dt

次のような出力が表示されます。

postgres=> \dt
                           List of relations
 Schema |         Name         | Type  |             Owner              
--------+----------------------+-------+--------------------------------
 public | cart_items           | table | 240900-linux-postgres-identity
 public | checkouts            | table | 240900-linux-postgres-identity
 public | collections          | table | 240900-linux-postgres-identity
 public | collections_products | table | 240900-linux-postgres-identity
 public | customers            | table | 240900-linux-postgres-identity
 public | delivery_methods     | table | 240900-linux-postgres-identity
 public | product_types        | table | 240900-linux-postgres-identity
 public | products             | table | 240900-linux-postgres-identity
 public | shipment_items       | table | 240900-linux-postgres-identity
 public | shipments            | table | 240900-linux-postgres-identity
 public | store_inventory      | table | 240900-linux-postgres-identity
 public | stores               | table | 240900-linux-postgres-identity
 public | suppliers            | table | 240900-linux-postgres-identity
 public | supply_orders        | table | 240900-linux-postgres-identity
(14 rows)

テーブルを一覧表示する SQL クエリを実行する

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public';

次のような出力が表示されます。

postgres=> SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public';
      table_name      
----------------------
 collections
 stores
 customers
 cart_items
 product_types
 products
 suppliers
 collections_products
 checkouts
 shipments
 delivery_methods
 shipment_items
 store_inventory
 supply_orders
(14 rows)

展開モードを有効にして、products テーブルから選択する

postgres=> プロンプトで、展開モードを有効にします:

\x

製品テーブルから選択してください。

select * from products;

次のプロンプトが表示されます:

postgres=> \x
Expanded display is on.
postgres=> select * from products;

製品の一覧が表示されます:

id                 | 1
product_type_id    | 1
supplier_id        | 2
sku                | brush_cleaner
name               | Meltdown Brush Cleaner
price              | 12.99
description        | We all leave our brushes sitting around, full of old dry paint. Don't worry! The Meltdown Brush Cleaner can remove just about anything.
image              | brush_cleaner.jpg
digital            | f
unit_description   | 1 - 10oz Jar
package_dimensions | 4x8x2
weight_in_pounds   | 3.2
reorder_amount     | 10
status             | in-stock
requires_shipping  | t
warehouse_location | Zone 1, Shelf 12, Slot 6
created_at         | ...
updated_at         | ...
...

結果をページングする Space キーを選択します。 q を押してページャーを終了します。

psql を終了する

\q

コマンド ラインを介してアプリケーションを対話的に実行する

リモート マシン上で、アプリケーションが格納されているディレクトリに移動します:

cd tailwind-traders-go/app

コマンド ラインから対話的にアプリケーションを実行します:

go run main.go app:serve

次のような出力が表示されます。

$ go run main.go app:serve
Listening on :8080

VM のパブリック IP アドレスを確認する

仮想マシンのパブリック IP アドレスを取得します:

IP_ADDRESS=$(az network public-ip show \
    --resource-group 240900-linux-postgres \
    --name vm-1-ip \
    --query ipAddress \
    --out tsv)

URL をターミナルに出力します:

echo "Your URL is: http://${IP_ADDRESS}:8080"

このユニットでは、対話型の開発/テスト目的でポート 8080 を使用します。 運用環境では、ポート 443 を使用し、エンドポイントへのトラフィックをセキュリティで保護するのに役立つ TLS 証明書が必要です。

パブリック API エンドポイントを参照する

Web ブラウザーで URL を開きます。 次のような出力が表示されます。

{
  "id": 5,
  "product_type_id": 1,
  "supplier_id": 2,
  "sku": "drafting_tools",
  "name": "Bespoke Drafting Set",
  "price": 45,
  "description": "Build your next bridge (or tunnel) using our Bespoke Drafting Set. Everyone drives across *regular* bridges everyday - but they'll rememeber yours - because it's _bespoke_.",
  "image": "drafting_tools.jpg",
  "digital": false,
  "unit_description": "Tools and carrying case",
  "package_dimensions": "5x10x3",
  "weight_in_pounds": "1.2",
  "reorder_amount": 10,
  "status": "in-stock",
  "requires_shipping": true,
  "warehouse_location": "Zone 1, Shelf 4, Slot 1",
  "created_at": "...",
  "updated_at": "..."
}

または、curl を使用して API エンドポイントに要求を行うこともできます:

curl "http://${IP_ADDRESS}:8080"

このエンドポイントは、データベースからランダムな製品を表示します。

ターミナルに記録された要求を表示する

アプリケーションを対話的に実行しているターミナルに戻ります。 出力には、API エンドポイントへの要求が表示されます:

{"time":"...","level":"INFO","msg":"httpLog","remoteAddr":"[::1]:58592","method":"GET","url":"/"}
{"time":"...","level":"INFO","msg":"httpLog","remoteAddr":"[::1]:59414","method":"GET","url":"/"}
{"time":"...","level":"INFO","msg":"httpLog","remoteAddr":"[::1]:59414","method":"GET","url":"/favicon.ico"}

これらの要求が成功すると、アプリケーション ワークロードを Azure Virtual Machines と Azure Database for PostgreSQL (フレキシブル サーバー) に移行する処理は無事完了しています。

Azure リソースをクリーンアップする

Linux と PostgreSQL のワークロードの確認が完了したら、コストを節約するためにリソースをクリーンアップします。

リソース グループ 240900-linux-postgres を削除するには、Azure portal を使用して手動で行うか、次の Azure CLI コマンドを実行します:

az group delete \
    --name 240900-linux-postgres \
    --yes \
    --no-wait

もう 1 つのオプションは、empty.bicep テンプレートを使用して、vm-postgres.bicep ファイルが作成したリソースを削除することです。 az deployment group create--mode Complete を実行すると、テンプレートで定義されていないリソースが削除されます。 empty.json にはリソースがないため、コマンドはすべてのリソースを削除します。

az deployment group create \
    --resource-group 240900-linux-postgres \
    --template-file deploy/empty.bicep \
    --mode Complete

empty.json をデプロイすると、240900-linux-postgres リソース グループはそのまま残ります。そのため、1 つのコマンドを使用してリソースを再度デプロイできます。

リソース