Azure導入メモ

Linux Virtual Machines の料金

パブリックIPのセクションで新規作成を選択するとIPアドレスのタイプを細かく指定できます。デフォルトでは静的IPが割当てられるため有料となります。 各クラウド サービスには、無料パブリック VIP が 1 つ与えられますがベーシックタイプの動的IP限定という条件が付きます。

下記のB1sタイプのVMインスタンスとSSDのP6タイプのストレージは12ヶ月無料ですが、グローバルIPの維持には原則料金が発生します。

動的IPアドレス:通常のVMではベーシックタイプの動的IPは無料。VM停止時にはIPが解放されるため再起動後のIPは変わります。VM(クラウドサービス)毎に無料の動的なパブリックIPを一つ充てがうことが出来ます。

静的IPアドレス:VMの稼働・停止に関わらずIPアドレスの維持に数ドル/月の費用が発生します。一度確保したIPは変わりません。

Azure リソースへのパブリック IP アドレスの割り当てに使用する IP アドレス範囲のリストは、「 Azure データセンターの IP アドレス範囲」で公開されています。

B1sは12ヶ月無料

インスタンスの各状態の説明

インスタンスを削除しない限り課金され続けます。

インスタンスの使用に対して課金されるかどうかを、次の表に示します。

電源状態 説明 課金
作成 仮想マシンがリソースを割り当て中です。 課金されません*
開始中 仮想マシンは起動中です。 課金されます
実行中 仮想マシンは完全に起動しました。 この状態が標準の動作状態です。 課金されます
停止中 この状態は、実行中と停止間で遷移している状態です。 課金されます
停止済み 仮想マシンはホスト上に割り当てられていますが、実行されていません。 PoweredOff 状態または 停止済み (割り当て済み) とも呼ばれます。 この状態は、PowerOff API 操作を呼び出すか、ゲスト OS 内からシャットダウンを呼び出すことによって発生することがあります。 VM の作成中、または “割り当て解除済み” 状態から VM を起動しているときに、“停止済み” 状態が一時的に検出されることもあります。 課金されます
割り当て解除中 この状態は、“実行中” と “割り当て解除済み” 間で遷移している状態です。 課金されません*
割り当て解除済み 仮想マシンは、基になるハードウェアに対するリースから解放され、電源が切られました。 この状態は、停止 (割り当て解除) とも呼ばれます。 課金されません*

Managed Disks の価格

Azure Virtual Machines および Azure VMware Solution で使用するために設定されているパフォーマンスが高く、非消費型のブロック ストレージ

LinuxのVMでOSにデフォルトで付与されるディスクサイズは30GB。VMインスタンス作成時にディスクタイプの指定は出来ますがサイズ指定は出来ません。

VMインスタンス作成後、停止してからサイズとタイプの変更が可能ですが、サイズを縮小する方向での変更は不可。

注)VMを停止してもVM料金、ディスク料金、ネットワーク料金は発生します。VMを削除した際はディスク、ネットワークも削除しないと課金され続けます。

一般用途ではスタンダードタイプのSSDを推奨します。

P6(プレミアムSSD、64GB)は12ヶ月無料

Azure Files の価格

コンテナインスタンスを使用する際の共有フォルダとしての利用など

送受信データ料金

受信は原則無料、インターネットへの送信は100GB/月まで無料

参考)無料枠データ転送についての質疑応答

IP アドレス の価格

Type Basic (クラシック) Basic (ARM) Standard (ARM) グローバル (ARM)
動的 IPv4 アドレス 最初のクラウド サービス VIP: 無料その他: $0.004/時間*1 $0.004/時間 該当なし 該当なし
静的 IPv4 アドレス $0.0036/時間*4 $0.0036/時間 $0.005/時間 $0.01/時間
パブリック IPv4 プレフィックス*2 該当なし 該当なし $0.006 (IP/時間単位)*3 $0.012 (IP/時間単位)*3

*1 すべてのインスタンス レベル パブリック IPv4 アドレス (ILPIP) は、$0.004/時間 で課金されます。各クラウド サービスには、無料パブリック VIP が 1 つ与えられます。追加の VIP は $0.004/時間 で課金されます。

*2 パブリック IPv4 プレフィックスは、連続するパブリック IPv4 アドレスの範囲です。カスタム IPv4 プレフィックス (BYOIP) から派生したパブリック IPv4 プレフィックスの使用には料金はかかりません。

*3 パブリック IPv4 プレフィックスは IPv4/時間単位で課金されます。プレフィックスが作成されるとすぐに課金されます。

*4 Azure VMware Solution で使用されるパブリック IPv4 アドレスの使用は、表示されている静的 IPv4 アドレスでの Basic (クラシック) に基づいて課金されます。

IPv6アドレス取得については無料

ネットワークインターフェイスIP構成(IPv4, IPv6)


ドキュメント

ストレージ概要

Data disk

A data disk is a managed disk that’s attached to a virtual machine to store application data, or other data you need to keep. Data disks are registered as SCSI drives and are labeled with a letter that you choose. Each data disk has a maximum capacity of 32,767 gibibytes (GiB). The size of the virtual machine determines how many data disks you can attach to it and the type of storage you can use to host the disks.

OS disk

Every virtual machine has one attached operating system disk. That OS disk has a pre-installed OS, which was selected when the VM was created. This disk contains the boot volume.

This disk has a maximum capacity of 4,095 GiB, however, many operating systems are partitioned with master boot record (MBR) by default. MBR limits the usable size to 2 TiB. If you need more than 2 TiB, create and attach data disks and use them for data storage. If you need to store data on the OS disk and require the additional space, convert it to GUID Partition Table (GPT). To learn about the differences between MBR and GPT on Windows deployments, see Windows and GPT FAQ.

Temporary disk

Most VMs contain a temporary disk, which is not a managed disk. The temporary disk provides short-term storage for applications and processes, and is intended to only store data such as page or swap files. Data on the temporary disk may be lost during a maintenance event or when you redeploy a VM. During a successful standard reboot of the VM, data on the temporary disk will persist. For more information about VMs without temporary disks, see Azure VM sizes with no local temporary disk.

On Azure Linux VMs, the temporary disk is typically /dev/sdb and on Windows VMs the temporary disk is D: by default. The temporary disk is not encrypted by server side encryption unless you enable encryption at host.


Azure 無料アカウントで無料サービスの使用状況を確認する

ホーム→サブスクリプション→利用状況別の上位無料サービス→全ての無料サービスを表示

から無料サービスの使用状況を確認できます。

ストレージ アカウントの概要

ストレージ アカウントの種類 サポートされているストレージ サービス 冗長オプション 使用
Standard 汎用 v2 BLOB Storage (Data Lake Storage *1 を含む)、Queue Storage、Table Storage、Azure Files ローカル冗長ストレージ (LRS)、geo 冗長ストレージ (GRS)、読み取りアクセス geo 冗長ストレージ (RA-GRS) ゾーン冗長ストレージ (ZRS)、geo ゾーン冗長ストレージ (GZRS)、読み取りアクセス geo ゾーン冗長ストレージ (RA-GZRS) *2 BLOB、ファイル共有、キュー、テーブル用の Standard タイプのストレージ アカウント。 Azure Storage を使用するほとんどのシナリオにお勧めします。 Azure Files の ネットワーク ファイル システム (NFS) のサポートが必要な場合は、Premium ファイル共有タイプのアカウントを使用してください。
Premium ブロック BLOB*3 Blob Storage (Data Lake Storage *1 を含む) LRSZRS*2 ブロック BLOB と追加 BLOB 用の Premium タイプのストレージ アカウント。 トランザクション レートが高く、比較的小さなオブジェクトが使用されるシナリオ、またはストレージ待ち時間が一貫して短いことが要求されるシナリオに推奨されます。 ワークロードの例に関する詳細情報を参照してください。
Premium ファイル共有*3 Azure Files LRS ZRS*2 ファイル共有専用の Premium タイプのストレージ アカウント。 エンタープライズまたはハイ パフォーマンス スケール アプリケーションにお勧めします。 サーバー メッセージ ブロック (SMB) ファイル共有と NFS ファイル共有の両方をサポートするストレージアカウントが必要な場合は、このタイプのアカウントを使用します。
Premium ページ BLOB*3 ページ BLOB のみ LRS ページ BLOB に特化した Premium Storage アカウントの種類。 ページ BLOB とサンプル ユース ケースの詳細情報を参照してください。

*1 Data Lake Storage は、Azure Blob Storage を基にした、ビッグ データ分析専用の機能のセットです。 詳細については、Data Lake Storage Gen2 の概要および Data Lake Storage Gen2 で使用するストレージ アカウントの作成に関するページを参照してください。

*2 ZRS、GZRS、RA-GZRS は、特定のリージョンの Standard 汎用 v2、Premium ブロック BLOB、Premium ファイル共有アカウントでのみ使用できます。 詳細については、「Azure Storage の冗長性」を参照してください。

*3 Premium パフォーマンス ストレージ アカウントでは、ソリッド ステート ドライブ (SSD) を使用することで低遅延と高スループットを実現しています。

VNet でどのアドレス範囲が使用できるでしょうか。

RFC 1918 で列挙されているアドレス範囲を使用することをお勧めします。これらの範囲は、プライベートのルーティング不能なアドレス空間用に、IETF によって留保されています。

  • 10.0.0.0 - 10.255.255.255 (10/8 プレフィックス)
  • 172.16.0.0 - 172.31.255.255 (172.16/12 プレフィックス)
  • 192.168.0.0 ~ 192.168.255.255 (192.168/16 プレフィックス)

また、Azure ではプライベート IP アドレス空間として扱われる、RFC 6598 で予約されている共有アドレス空間をデプロイすることもできます。

  • 100.64.0.0 ~ 100.127.255.255 (100.64/10 プレフィックス)

IETF で認識されるプライベートでルーティング不可能な他のすべてのアドレス空間を含む、他のアドレス空間は機能する可能性がありますが、望ましくない副作用が発生する可能性があります。

さらに、以下のアドレス範囲は追加できません。

  • 224.0.0.0/4 (マルチキャスト)
  • 255.255.255.255/32 (ブロードキャスト)
  • 127.0.0.0/8 (ループバック)
  • 169.254.0.0/16 (リンク ローカル)
  • 168.63.129.16/32 (内部 DNS)

Comparing security groups in AWS and Azure

1.Azure, we apply NSG(Network Security Groups) at subnet or individual NIC level(VM) whereas in AWS these can only be applied at individual VM level.
NACL is applied at subnet level in AWS.

2.Azure, we have a column for source and destination IP address(for each of inbound and outbound categories).

I infer that due to Security Groups being applied at VM level in AWS, we define only destination IP for outbound rules(src being the VM) and source IP for inbound rules(dst being the VM).

Further,even for NACL in AWS, for inbound rule,only src IP can be defined .For outbound rule,only dst IP can be defined.

3.(AWS)Irrespective of inbound/outbound rules segregation, ‘port’ always refers to ‘destination’ side which listens on a specific port for traffic.
{This is usually the case with clients using a random port to connect to a server on a specific port like 80}

And unlike Azure, we cannot define both ‘to’ and ‘from’ ports while configuring inbound/outbound rules?
(in particular, we cannot define ‘source’ ports under either inbound/outbound section).

4.AWS defines only Allow rules whereas Azure has options for both allow and deny(security group).
Further,AWS has NACL which can contain both allow and deny statements.

5.Both AWS and Azure have ‘stateful’ concept, meaning an explicit rule for ‘return’ traffic response is not needed(define rules for only who gets to initiate the communication)—for security groups.

In AWS,we have NACL concept which is stateless,ie rules needed in both direction for communication to be successful.

ネットワーク セキュリティ グループ

プロパティ 説明
名前 ネットワーク セキュリティ グループ内で一意の名前。
Priority 100 ~ 4096 の数値。 規則は、優先順位に従って処理され、数値が小さいほど優先順位が高いために、大きい数値の前に小さい数値が処理されます。 トラフィックが規則に一致すると、処理が停止します。 この結果、優先順位低く (数値が大きい)、優先順位が高い規則と同じ属性を持つ規則は処理されません。
ソース/宛先 個別 IP アドレス、クラスレス ドメイン間ルーティング (CIDR) ブロック (例: 10.0.0.0/24)、サービス タグ、またはアプリケーション セキュリティ グループ。 Azure リソースのアドレスを指定する場合は、そのリソースに割り当てられているプライベート IP アドレスを指定します。 受信トラフィックの場合、ネットワーク セキュリティ グループが処理されるタイミングは、Azure でパブリック IP アドレスがプライベート IP アドレスに変換された後です。送信トラフィックの場合は、Azure でプライベート IP アドレスがパブリック IP アドレスに変換される前になります。 範囲、サービス タグ、またはアプリケーション セキュリティ グループを指定すると、必要なセキュリティ規則の数が少なくなります。 規則内で複数の個別 IP アドレスと範囲 (複数のサービス タグまたはアプリケーション グループは指定できません) を指定する機能は、拡張セキュリティ規則と呼ばれています。 拡張セキュリティ規則は、Resource Manager デプロイ モデルで作成されたネットワーク セキュリティ グループでのみ作成できます。 クラシック デプロイ モデルで作成されたネットワーク セキュリティ グループで、複数の IP アドレスおよび IP アドレス範囲を指定することはできません。
Protocol TCP、UDP、ICMP、ESP、AH、または Any。 現在、ESP と AH のプロトコルは Azure Portal では使用できませんが、ARM テンプレートでは使用できます。
Direction 規則が受信トラフィックまたは送信トラフィックに適用されるかどうか。
ポートの範囲 個別のポートまたはポートの範囲を指定できます。 たとえば、80 や 10000-10005 などと指定できます。 範囲を指定すると、作成するセキュリティ規則の数を減らすことができます。 拡張セキュリティ規則は、Resource Manager デプロイ モデルで作成されたネットワーク セキュリティ グループでのみ作成できます。 クラシック デプロイ モデルで作成されたネットワーク セキュリティ グループで、複数のポートまたはポート範囲を指定することはできません。
アクション 許可または拒否

高度なトラブルシューティング

" 仮想マシン エージェントの状態が準備できていません " について

WireServer IP に接続できない (ホスト IP)

VM がホスト サーバーの WireServer IP に到達できない場合、 /var/log/waagent.log ファイルに次のエラーが表示されます。

2020-10-02T18:11:13.148998Z WARNING ExtHandler ExtHandler An error occurred while retrieving the goal state:

上記エラーを検出

$ cat /var/log/waagent.log | grep error
    protocol.update_goal_state(silent=self._update_goal_state_error_count >= max_errors_to_log)
    logger.warn(textutil.format_exception(error))
    raise ResourceGoneError(response_error)
    message = u"An error occurred while retrieving the goal state: {0}".format(textutil.format_exception(e))
    logger.warn(textutil.format_exception(error))

この問題を解決するには

  • SSH を使用して VM に接続し、次のコマンドを実行して VM と WireServer の間の接続をテストします。 コマンドを実行するには、ルート特権が必要です。
curl http://168.63.129.16/?comp=versions
  • ファイアウォール、プロキシ、または IP アドレス 168.63.129.16 へのアクセスをブロックしている可能性がある別のソースによって発生する可能性がある問題を確認します。
  • Linux iptables(nftables) またはサード パーティファイアウォールがポート 80 および 32526 へのアクセスをブロックしているかどうかを確認します。

nftablesの設定追加, VMのネットワークポート設定(32526/tcp)


IP アドレス 168.63.129.16 とは

IP アドレス 168.63.129.16 は、Azure プラットフォーム リソースへの通信チャネルの使用を容易にするために使用される仮想パブリック IP アドレスです。 お客様は、Azure でプライベート仮想ネットワーク用に任意のアドレス空間を定義できます。 そのため、Azure プラットフォーム リソースは、一意のパブリック IP アドレスとして提供される必要があります。 この仮想パブリック IP アドレスによって、次のことが容易になります。

  • VM エージェントが Azure プラットフォームと通信して、それが “準備完了” 状態にあることを通知できるようにする。
  • カスタム DNS サーバーが存在しないリソース (VM など) にフィルター処理された名前解決を提供するために、DNS 仮想サーバーとの通信を有効にする。 このフィルター処理により、お客様が自分のリソースのホスト名だけを解決できるようになります。
  • Azure Load Balancer の正常性プローブが VM の正常性状態を特定できるようにする。
  • VM が、Azure の DHCP サービスから動的 IP アドレスを取得できるようにします。
  • PaaS ロールに対するゲスト エージェントのハートビート メッセージを有効にする。

168.63.129.16 への通信をテスト

tracerouteのインストール

$ sudo apt install traceroute

テストフロー

$ echo "Testing 80 168.63.129.16 Port 80" > 168-63-129-16_test.txt
$ sudo traceroute -T -p 80 168.63.129.16 >> 168-63-129-16_test.txt
$ echo "Testing 80 168.63.129.16 Port 32526" >> 168-63-129-16_test.txt
$ sudo traceroute -T -p 32526 168.63.129.16 >> 168-63-129-16_test.txt
$ echo "Test 168.63.129.16 Versions"  >> 168-63-129-16_test.txt
$ sudo curl http://168.63.129.16/?comp=versions >> 168-63-129-16_test.txt

テキストファイルの中身を確認して以下のような内容であるか確認して下さい。

$ cat 168-63-129-16_test.txt
traceroute -T -p 80 168.63.129.16
traceroute to 168.63.129.16 (168.63.129.16), 30 hops max, 60 byte packets
1  168.63.129.16 (168.63.129.16)  0.974 ms  1.085 ms  1.078 ms

traceroute -T -p 32526 168.63.129.16
traceroute to 168.63.129.16 (168.63.129.16), 30 hops max, 60 byte packets
1  168.63.129.16 (168.63.129.16)  0.883 ms  1.004 ms  1.010 ms
	
curl http://168.63.129.16/?comp=versions
<?xml version="1.0" encoding="utf-8"?>
<Versions>
<Preferred>
<Version>2015-04-05</Version>
</Preferred>
<Supported>
<Version>2015-04-05</Version>
<Version>2012-11-30</Version>
<Version>2012-09-15</Version>
<Version>2012-05-15</Version>
<Version>2011-12-31</Version>
<Version>2011-10-15</Version>
<Version>2011-08-31</Version>
<Version>2011-04-07</Version>
<Version>2010-12-15</Version>
<Version>2010-28-10</Version>
</Supported>

VM - DNS unable to resolve

デフォルトのネットワークセキュリティルールでは、AzureのVMに付与されたグローバルIP向けのICPMプロトコルは拒否されます。試験などの際にpingコマンドを許可するためには、ICPMを許可する新たなルール設定を追加する必要があります。

VMのネットワークについて

ネットワークインターフェイス

インターネットにつながるパブリックIPが付与されるインターフェイス( eth0 など)。
ネットワークセキュリティグループ(プロトコルとポートの制限ルール)は、デフォルトでこのインターフェイスに付与されます。DNSサーバは下記のサブネットで指定したもの、または任意で指定可。サブネットからVMに付与されるローカルIPのアドレスは xx.xx.xx.0/24 の範囲内から。

仮想ネットワーク/サブネット

アドレス空間 xx.xx.0.0/16 のサブネットワーク。ネットワークセキュリティグループは任意。DNSサーバはAzure提供のものか任意で指定可。

Windows (Windows Server 2016 Datacenter)のVMインスタンス作成

Linuxユーザにとって使用するメリットはありませんが、一年間無料なので、課金トラップに気をつけつつ試用することにしました(powershellのマスターなど別コストが発生するためお勧めしません)。

12ヶ月無料サービスの上記Windows Sever VMインスタンスを作成 (Standard B1s, Premium SSD 64GB)

サーバ管理は Windows Admin Center による(ページ内でインストール可)。

標準ユーザが Windows Admin Center へアクセスできるロールを付与する必要あり。


ロールの割当:アクセス制御(IAM)

アクセス制御(IAM) → ロールの割当の追加 → 検索窓から"windows" で検索

Windows Admin Center Administrator Loginが検索結果に表示されます。メンバータグからユーザを選択 → レビューと割り当てタグへと進んで割当手続きを完了して下さい。

ポートの開放

ネットワーク→受信ポートの規則で6516ポートを開放(許可)します。

アクセス権とポート開放に問題なければ、以下の Windows Admin Center へログイン出来ます。


PowerShellドキュメント

Ubuntu への PowerShell のインストール

PowerShellパッケージレポジトリ
https://www.powershellgallery.com/

How to Install VPN on Windows Server 2016

RemoteAccess

VPNサーバは以下のRemoteAccessに含まれているようです。

PowerShellでのインストール

Azure CLIのインストール

以下のシェルスクリプトでインストール可。他のインストールオプションについては下記参照のこと。

$ curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

以下ログインコマンドでデフォルトブラウザにログイン認証画面が表示されます。
ログイン

$ az login

Azure CLIドキュメント

IPv6のアドレス空間を追加したサブネットの作成

仮想ネットワーク→アドレス空間

VMのネットワークメニューから仮想ネットワーク/サブネットをクリックします。

IPv6のアドレス空間(範囲)を指定して追加

仮想ネットワーク→サブネット

+サブネットから上記IPv6のアドレス空間を追加した新たなサブネットを作成

左側メニューの接続デバイスから以下の画面に切替えます。

仮想ネットワーク→接続デバイス

接続デバイスを選択します。

以下のネットワークインターフェイスの画面に切替わるので、このページからIP構成を選択します。

ネットワークインターフェイス→IP構成

上記で作成したIPv6のアドレス範囲を含むサブネットを選択して保存して下さい。

Windows Server 2016 VMリモートデスクトップによる接続

AzureのWindows Serverインスタンスへの推奨接続方法はリモートデスクトップ(RDP)によるものなので、Ubuntuの標準リモートデスクトップアプリである Remmina を使用して接続します。RDP接続に必要なポート番号:3389は予め開放しておきます。

注) 接続する前に、接続先で使用するキーボードのレイアウト (Japanese) を指定して下さい。

まず初めに Remmina でインポートする接続先情報が記載されたRDPファイルをダウンロードします。

次に Remmina を起動して上記ダウンロードしたRDPファイルをインポートして下さい。

インポートすると接続先リストが表示されるので、ここをダブルクリックして仮想マシン作成時に指定したユーザ名とパスワードを入力(パスワードを忘れた場合はヘルプのパスワードリセットから変更可)すると…

以下のWindowsコンソールが表示されます。ここから各コマンドを打ち込みます。

PowerShell はこのコンソールから起動します。

WIndows Server 2016 PowerShell リファレンス

Windowsコマンドリファレンス

Azure Windows Server 2016 VMにPowerShellでDockerをインストール

Provider:DockerMsftProvider(OS:Windowsのみ対応 )

Provider:DockerProvider(OS:Linux対応、Hyper-Vの設定が必要なこととインスタンスのメモリ条件が4GBとコストがかかります)

トラブルシュート

WARNING: Unable to resolve package source ‘https://www.powershellgallery.com/api/v2’.
PackageManagement\Install-Package : No match was found for the specified search criteria

PS > [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Update-Module : Module ‘PowershellGet’ was not installed by using Install-Module, so it cannot be
updated.

PS > Install-Module PowerShellGet -Force

Hyper-V

wget, curl = Invoke-WebRequest

Linuxで標準的に使用されるコマンド(アプリ)の一部はエイリアスとして実装されているようです。wgetはInvoke-WebRequestのエイリアスです。

Get-Alias または Get-Command で確認できます。

PS C:\Users\takanobu> Get-Alias -Name wget

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           wget -> Invoke-WebRequest
PS C:\Users\takanobu> Get-Alias -Definition Invoke-Webrequest

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           curl -> Invoke-WebRequest
Alias           iwr -> Invoke-WebRequest
Alias           wget -> Invoke-WebRequest
PS C:\Users\takanobu> get-command wget

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           wget -> Invoke-WebRequest

ex) nginxのzipファイルをダウンロード

PS > Invoke-WebRequest -Uri https://nginx.org/download/nginx-1.23.2.zip -Outfile ./nginx.zip

unzip:Expand-Archive

unzipコマンドのエイリアスは設定されていないようです。
Expand-Archive を使用します。

PS > Expand-Archive C:\a.zip -DestinationPath C:\a

cat

catGet-Content のエイリアスとして設定されています。

PS C:\Users\takanobu\nginx\nginx-1.23.2> get-command cat

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cat -> Get-Content

Nginx for Windows

Nginx for Windows
https://nginx.org/en/docs/windows.html

ダウンロード
https://nginx.org/en/download.html

ダウンロード先フォルダは任意。展開したフォルダー内で起動コマンド start nginx を実行
ex)

PS > Invoke-WebRequest -Uri https://nginx.org/download/nginx-1.23.2.zip -Outfile ./nginx.zip
PS > Expand-Archive nginx.zip
PS > cd nginx/nginx-1.23.2
PS > start nginx

PowerShellでは nginx ---> ./nginx.exe とすること。Windowsのコンソールではそのまま使用可。

Commands Description
nginx -s stop fast shutdown
nginx -s quit graceful shutdown
nginx -s reload changing configuration, starting new worker processes with a new configuration, graceful shutdown of old worker processes
nginx -s reopen re-opening log files

プロセス確認

PS > tasklist /fi "imagename eq nginx.exe"

Image Name           PID Session Name     Session#    Mem Usage
=============== ======== ============== ========== ============
nginx.exe            652 Console                 0      2 780 K
nginx.exe           1332 Console                 0      3 112 K

Invoke-WebRequestcurlのエイリアス)で動作確認

> invoke-webrequest -uri http://localhost -usebasicparsing


StatusCode        : 200
StatusDescription : OK
Content           : <!DOCTYPE html>
                    <html>
                    <head>
                    <title>Welcome to nginx!</title>
                    <style>
                    html { color-scheme: light dark; }
                    body { width: 35em; margin: 0 auto;
                    font-family: Tahoma, Verdana, Arial, sans-serif; }
                    </style...
RawContent        : HTTP/1.1 200 OK
                    Connection: keep-alive
                    Accept-Ranges: bytes
                    Content-Length: 615
                    Content-Type: text/html
                    Date: Thu, 01 Dec 2022 14:30:26 GMT
                    ETag: "634fe5e6-267"
                    Last-Modified: Wed, 19 Oct 2022 ...
Forms             :
Headers           : {[Connection, keep-alive], [Accept-Ranges, bytes], [Content-Length, 615], [Content-Type,
                    text/html]...}
Images            : {}
InputFields       : {}
Links             : {@{outerHTML=<a href="http://nginx.org/">nginx.org</a>; tagName=A;
                    href=http://nginx.org/}, @{outerHTML=<a href="http://nginx.com/">nginx.com</a>; tagName=A;
                    href=http://nginx.com/}}
ParsedHtml        :
RawContentLength  : 615

Get-NetIPConfiguration

PS > Get-NetIPpConfiguration

InterfaceAlias       : vEthernet (HNS Internal NIC)
InterfaceIndex       : 11
InterfaceDescription : Hyper-V Virtual Ethernet Adapter
NetProfile.Name      : Unidentified network
IPv4Address          : 172.19.112.1
IPv6DefaultGateway   :
IPv4DefaultGateway   :
DNSServer            : fec0:0:0:ffff::1
                       fec0:0:0:ffff::2
                       fec0:0:0:ffff::3

InterfaceAlias       : Ethernet
InterfaceIndex       : 5
InterfaceDescription : Microsoft Hyper-V Network Adapter
NetProfile.Name      : Network
IPv4Address          : 10.1.1.4
IPv6DefaultGateway   :
IPv4DefaultGateway   : 10.1.1.1
DNSServer            : 168.63.129.16

Get-NetAdapter

PS > Get-NetAdapter

Name                      InterfaceDescription                    ifIndex Status       MacAddress        LinkSp
                                                                                                            eed
----                      --------------------                    ------- ------       ----------        ------
vEthernet (HNS Interna... Hyper-V Virtual Ethernet Adapter             11 Up           00-15-5D-4F-12-1E ...bps
Ethernet                  Microsoft Hyper-V Network Adapter             5 Up           00-0D-3A-50-D8-47 ...bps

Firewallによるリモートアクセス制限

ローカルネットワーク内ではアクセスできるが、リモートからアクセスができない場合、Windows Serverのファイヤーウォールが原因です。以下の3種類のプロフィールでルール設定されています。

  1. Domain profile: Used for networks where there’s a system of account authentication against an Active Directory domain controller
  2. Private profile: Designed for and best used in private networks such as a home network
  3. Public profile: Designed with higher security in mind for public networks, like Wi-Fi hotspots, coffee shops, airports, hotels, or stores

オプションは多いので、取り敢えずファイヤーウォールルールを除外します。

PS > Set-NetFirewallProfile -All -Enabled False

ネットセキュリティコマンド一覧

PS > Get-Command -Module NetSecurity

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Copy-NetFirewallRule                               2.0.0.0    NetSecurity
Function        Copy-NetIPsecMainModeCryptoSet                     2.0.0.0    NetSecurity
Function        Copy-NetIPsecMainModeRule                          2.0.0.0    NetSecurity
Function        Copy-NetIPsecPhase1AuthSet                         2.0.0.0    NetSecurity
Function        Copy-NetIPsecPhase2AuthSet                         2.0.0.0    NetSecurity
Function        Copy-NetIPsecQuickModeCryptoSet                    2.0.0.0    NetSecurity
Function        Copy-NetIPsecRule                                  2.0.0.0    NetSecurity
Function        Disable-NetFirewallRule                            2.0.0.0    NetSecurity
Function        Disable-NetIPsecMainModeRule                       2.0.0.0    NetSecurity
Function        Disable-NetIPsecRule                               2.0.0.0    NetSecurity
Function        Enable-NetFirewallRule                             2.0.0.0    NetSecurity
Function        Enable-NetIPsecMainModeRule                        2.0.0.0    NetSecurity
Function        Enable-NetIPsecRule                                2.0.0.0    NetSecurity
Function        Find-NetIPsecRule                                  2.0.0.0    NetSecurity
Function        Get-NetFirewallAddressFilter                       2.0.0.0    NetSecurity
Function        Get-NetFirewallApplicationFilter                   2.0.0.0    NetSecurity
Function        Get-NetFirewallInterfaceFilter                     2.0.0.0    NetSecurity
Function        Get-NetFirewallInterfaceTypeFilter                 2.0.0.0    NetSecurity
Function        Get-NetFirewallPortFilter                          2.0.0.0    NetSecurity
Function        Get-NetFirewallProfile                             2.0.0.0    NetSecurity
Function        Get-NetFirewallRule                                2.0.0.0    NetSecurity
Function        Get-NetFirewallSecurityFilter                      2.0.0.0    NetSecurity
Function        Get-NetFirewallServiceFilter                       2.0.0.0    NetSecurity
Function        Get-NetFirewallSetting                             2.0.0.0    NetSecurity
Function        Get-NetIPsecDospSetting                            2.0.0.0    NetSecurity
Function        Get-NetIPsecMainModeCryptoSet                      2.0.0.0    NetSecurity
Function        Get-NetIPsecMainModeRule                           2.0.0.0    NetSecurity
Function        Get-NetIPsecMainModeSA                             2.0.0.0    NetSecurity
Function        Get-NetIPsecPhase1AuthSet                          2.0.0.0    NetSecurity
Function        Get-NetIPsecPhase2AuthSet                          2.0.0.0    NetSecurity
Function        Get-NetIPsecQuickModeCryptoSet                     2.0.0.0    NetSecurity
Function        Get-NetIPsecQuickModeSA                            2.0.0.0    NetSecurity
Function        Get-NetIPsecRule                                   2.0.0.0    NetSecurity
Function        New-NetFirewallRule                                2.0.0.0    NetSecurity
Function        New-NetIPsecDospSetting                            2.0.0.0    NetSecurity
Function        New-NetIPsecMainModeCryptoSet                      2.0.0.0    NetSecurity
Function        New-NetIPsecMainModeRule                           2.0.0.0    NetSecurity
Function        New-NetIPsecPhase1AuthSet                          2.0.0.0    NetSecurity
Function        New-NetIPsecPhase2AuthSet                          2.0.0.0    NetSecurity
Function        New-NetIPsecQuickModeCryptoSet                     2.0.0.0    NetSecurity
Function        New-NetIPsecRule                                   2.0.0.0    NetSecurity
Function        Open-NetGPO                                        2.0.0.0    NetSecurity
Function        Remove-NetFirewallRule                             2.0.0.0    NetSecurity
Function        Remove-NetIPsecDospSetting                         2.0.0.0    NetSecurity
Function        Remove-NetIPsecMainModeCryptoSet                   2.0.0.0    NetSecurity
Function        Remove-NetIPsecMainModeRule                        2.0.0.0    NetSecurity
Function        Remove-NetIPsecMainModeSA                          2.0.0.0    NetSecurity
Function        Remove-NetIPsecPhase1AuthSet                       2.0.0.0    NetSecurity
Function        Remove-NetIPsecPhase2AuthSet                       2.0.0.0    NetSecurity
Function        Remove-NetIPsecQuickModeCryptoSet                  2.0.0.0    NetSecurity
Function        Remove-NetIPsecQuickModeSA                         2.0.0.0    NetSecurity
Function        Remove-NetIPsecRule                                2.0.0.0    NetSecurity
Function        Rename-NetFirewallRule                             2.0.0.0    NetSecurity
Function        Rename-NetIPsecMainModeCryptoSet                   2.0.0.0    NetSecurity
Function        Rename-NetIPsecMainModeRule                        2.0.0.0    NetSecurity
Function        Rename-NetIPsecPhase1AuthSet                       2.0.0.0    NetSecurity
Function        Rename-NetIPsecPhase2AuthSet                       2.0.0.0    NetSecurity
Function        Rename-NetIPsecQuickModeCryptoSet                  2.0.0.0    NetSecurity
Function        Rename-NetIPsecRule                                2.0.0.0    NetSecurity
Function        Save-NetGPO                                        2.0.0.0    NetSecurity
Function        Set-NetFirewallAddressFilter                       2.0.0.0    NetSecurity
Function        Set-NetFirewallApplicationFilter                   2.0.0.0    NetSecurity
Function        Set-NetFirewallInterfaceFilter                     2.0.0.0    NetSecurity
Function        Set-NetFirewallInterfaceTypeFilter                 2.0.0.0    NetSecurity
Function        Set-NetFirewallPortFilter                          2.0.0.0    NetSecurity
Function        Set-NetFirewallProfile                             2.0.0.0    NetSecurity
Function        Set-NetFirewallRule                                2.0.0.0    NetSecurity
Function        Set-NetFirewallSecurityFilter                      2.0.0.0    NetSecurity
Function        Set-NetFirewallServiceFilter                       2.0.0.0    NetSecurity
Function        Set-NetFirewallSetting                             2.0.0.0    NetSecurity
Function        Set-NetIPsecDospSetting                            2.0.0.0    NetSecurity
Function        Set-NetIPsecMainModeCryptoSet                      2.0.0.0    NetSecurity
Function        Set-NetIPsecMainModeRule                           2.0.0.0    NetSecurity
Function        Set-NetIPsecPhase1AuthSet                          2.0.0.0    NetSecurity
Function        Set-NetIPsecPhase2AuthSet                          2.0.0.0    NetSecurity
Function        Set-NetIPsecQuickModeCryptoSet                     2.0.0.0    NetSecurity
Function        Set-NetIPsecRule                                   2.0.0.0    NetSecurity
Function        Show-NetFirewallRule                               2.0.0.0    NetSecurity
Function        Show-NetIPsecRule                                  2.0.0.0    NetSecurity
Function        Sync-NetIPsecRule                                  2.0.0.0    NetSecurity
Function        Update-NetIPsecRule                                2.0.0.0    NetSecurity
Cmdlet          Get-DAPolicyChange                                 2.0.0.0    NetSecurity
Cmdlet          New-NetIPsecAuthProposal                           2.0.0.0    NetSecurity
Cmdlet          New-NetIPsecMainModeCryptoProposal                 2.0.0.0    NetSecurity
Cmdlet          New-NetIPsecQuickModeCryptoProposal                2.0.0.0    NetSecurity

PowerShellによるルール設定

以下のサイトを参考にデフォルトのファイアーウォールルールを除外せずに新規ルール (ポート番号80,443の開放)New-NetFirewallRule により作成します。

New-NetFirewallRule

PS > New-NetFirewallRule -DisplayName 'HTTP-Inbound' -Direction Inbound -Action Allow -Protocol TCP -LocalPort @('80', '443')

Name                  : {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
DisplayName           : HTTP-Inbound
Description           :
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Any
Platform              : {}
Direction             : Inbound
Action                : Allow
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False
Owner                 :
PrimaryStatus         : OK
Status                : The rule was parsed successfully from the store. (65536)
EnforcementStatus     : NotApplicable
PolicyStoreSource     : PersistentStore
PolicyStoreSourceType : Local

ルールを除外する場合 Remove-NetFirewallRule

PS > Remove-NetFirewallRule -DisplayName 'HTTP-Inbound'

SConfig

Server Configuration

PS > SConfig

Certbotのインストール

PowerShellの操作にまだ慣れていないため、Windowsコンソールと行き来します。
本来はPowerShellだけの操作で完結する筈です。

PowerShellで任意のディレクトリにダウンロード

PS > invoke-webrequest -uri https://dl.eff.org/certbot-beta-installer-win_amd64.exe -outfile ./certbot-beta-installer-win_amd64.exe

Windowsコンソールに戻りインストーラーを実行

C:\ > certbot-beta-installer-win_amd64.exe

取り敢えずヘルプで動作確認

C:\ > "program files/certbot/bin/certbot" --help
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  certbot [SUBCOMMAND] [options] [-d DOMAIN] [-d DOMAIN] ...

Certbot can obtain and install HTTPS/TLS/SSL certificates.  By default,
it will attempt to use a webserver both for obtaining and installing the
certificate. The most common SUBCOMMANDS and flags are:

obtain, install, and renew certificates:
    (default) run   Obtain & install a certificate in your current webserver
    certonly        Obtain or renew a certificate, but do not install it
    renew           Renew all previously obtained certificates that are near
expiry
    enhance         Add security enhancements to your existing configuration
   -d DOMAINS       Comma-separated list of domains to obtain a certificate for
.....
.....

スタンドアローンモードで認証手続き

注) メールアドレスとドメインの入力が必要。認証取得には、ポート:80をオープンにする必要があるため、ウェブサーバ等は停止してから実行すること。

以下のディレクトリに認証ファイルが保存されます。

C:\ > "program files/certbot/bin/certbot" certonly --standalone
.....
.....
Successfully received certificate.
Certificate is saved at: C:\Certbot\live\ficus.myvnc.com\fullchain.pem
Key is saved at:         C:\Certbot\live\ficus.myvnc.com\privkey.pem
.....
.....

Windowsにインストールされたnginxのディレクトリ構成は以下の通りです。

C:\nginx\nginx-1.23.2 > dir
 Volume in drive C is Windows
 Volume Serial Number is 58AD-4A66

 Directory of C:\nginx\nginx-1.23.2

12/03/2022  05:07 AM    <DIR>          .
12/03/2022  05:07 AM    <DIR>          ..
12/03/2022  12:22 AM    <DIR>          conf
12/01/2022  08:15 AM    <DIR>          contrib
12/01/2022  08:15 AM    <DIR>          docs
12/03/2022  05:23 AM    <DIR>          html
12/03/2022  02:48 AM    <DIR>          logs
10/19/2022  01:38 PM         3,799,552 nginx.exe
12/01/2022  08:15 AM    <DIR>          temp
               2 File(s)      3,799,556 bytes
               8 Dir(s)  23,975,211,008 bytes free

conf.dは後から作成。ここにプロキシーサーバとして使用するための設定ファイルを格納します。

C:\nginx\nginx-1.23.2 > dir conf
 Volume in drive C is Windows
 Volume Serial Number is 58AD-4A66

 Directory of C:\nginx\nginx-1.23.2\conf

12/03/2022  12:22 AM    <DIR>          .
12/03/2022  12:22 AM    <DIR>          ..
12/03/2022  02:34 AM    <DIR>          conf.d
10/19/2022  01:39 PM             1,103 fastcgi.conf
10/19/2022  01:39 PM             1,032 fastcgi_params
10/19/2022  01:39 PM             2,946 koi-utf
10/19/2022  01:39 PM             2,326 koi-win
10/19/2022  01:39 PM             5,448 mime.types
12/03/2022  02:15 PM               731 nginx.conf
10/19/2022  01:39 PM               653 scgi_params
10/19/2022  01:39 PM               681 uwsgi_params
10/19/2022  01:39 PM             3,736 win-utf
               9 File(s)         18,656 bytes
               3 Dir(s)  23,979,286,528 bytes free

C:\ > notepad conf/nginx.conf

pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    include conf.d/*.conf;

}

C:\ > notepad conf/conf.d/default.conf (リバースプロキシとして設定)

server {
    server_name ficus.myvnc.com;
    server_tokens off;
    # access_log  /var/log/nginx/access.log;
    # error_log   /var/log/nginx/error.log error;

    location / {
        proxy_pass https://xx.xx.xx.xx:8080;
        proxy_set_header Host ficus.myvnc.com;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

    }

    listen 443 ssl;
    ssl_certificate C:\Certbot\live\ficus.myvnc.com\fullchain.pem;
    ssl_certificate_key C:\Certbot\live\ficus.myvnc.com\privkey.pem;
    include C:\Certbot\options-ssl-nginx.conf;
    #ssl_dhparam C:\Certbot\ssl-dhparams.pem; 
}


server {
    if ($host = ficus.myvnc.com) {
        return 301 https://$host$request_uri;
    } 

    server_name ficus.myvnc.com;

    listen 80;
    return 404; 

}

追加 C:\ > notepad \Certbot\options-ssl-nginx.conf

# This file contains important security parameters. If you modify this file
# manually, Certbot will be unable to automatically provide future security
# updates. Instead, Certbot will print and log an error message with a path to
# the up-to-date file that you will need to refer to when manually updating
# this file.

ssl_session_cache shared:le_nginx_SSL:10m;
ssl_session_timeout 1440m;
ssl_session_tickets off;

ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;

ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384";

設定ファイルのリロード

C:\ > nginx -s reload

:poop:ウーン、Windowsは面倒くさい!!! :face_with_symbols_over_mouth:

OpenSSL for Windows

OpenSSL Wikiによると幾つかのサイトでバイナリが配布されています。
https://wiki.openssl.org/index.php/Binaries

今回は以下のサイトからインストーラをダウンロード。
https://slproweb.com/products/Win32OpenSSL.html

Win64 OpenSSL v3.0.7 Light

PS C:\> Invoke-WebRequest -Uri https://slproweb.com/download/Win64OpenSSL_Light-3_0_7.exe -Outfile ./Win64OpenSSL_Light-3_0_7.exe

インストール

PS C:\> .\Win64OpenSSL_Light-3_0_7.exe

Windowsコンソールでバイナリファイル openssl.exe 確認

C:\> dir "\program files\OpenSSl-Win64\bin"
 Volume in drive C is Windows
 Volume Serial Number is 58AD-4A66

 Directory of C:\program files\OpenSSl-Win64\bin

12/04/2022  02:53 AM    <DIR>          .
12/04/2022  02:53 AM    <DIR>          ..
11/01/2022  10:14 AM             8,299 CA.pl
11/01/2022  10:14 AM            71,168 capi.dll
11/01/2022  10:14 AM            46,592 dasync.dll
11/01/2022  10:14 AM           157,184 legacy.dll
11/01/2022  10:14 AM         5,140,992 libcrypto-3-x64.dll
11/01/2022  10:14 AM           776,192 libssl-3-x64.dll
11/01/2022  10:14 AM            83,456 loader_attic.dll
11/01/2022  10:14 AM           717,824 openssl.exe
11/01/2022  10:14 AM            49,152 ossltest.dll
11/01/2022  10:14 AM            58,368 padlock.dll
12/04/2022  02:53 AM    <DIR>          PEM
11/01/2022  10:14 AM             7,638 progs.pl
11/01/2022  10:14 AM            38,400 p_test.dll
11/01/2022  10:14 AM             6,946 tsget.pl
              13 File(s)      7,162,211 bytes
               3 Dir(s)  24,056,950,784 bytes free

dhparam.pem の作成

C:\ > "\program files\OpenSSl-Win64\bin\openssl" dhparam -out \Certbot\dhparam.pem 4096

このファイルをnginxのsslのセクションで指定してセキュリティを高めて下さい。

conf/conf.d/default.conf

.....
.....

listen 443 ssl;
    ssl_certificate C:\Certbot\live\ficus.myvnc.com\fullchain.pem;
    ssl_certificate_key C:\Certbot\live\ficus.myvnc.com\privkey.pem;
    include C:\Certbot\options-ssl-nginx.conf;
    ssl_dhparam C:\Certbot\dhparam.pem;

.....
.....

タスクスケジュール管理

各アプリのタスクスケジューラへの登録

前記事でインストールしたCertbotの更新コマンド (certbot renew)は、インストール時にタスクスケジューラへ登録されているようです。

PS > Get-ScheduledTask

TaskPath                                       TaskName                          State
--------                                       --------                          -----
\                                              Certbot Renew Task                Ready
\Microsoft\Windows\.NET Framework\             .NET Framework NGEN v4.0.30319    Ready
\Microsoft\Windows\.NET Framework\             .NET Framework NGEN v4.0.30319 64 Ready

.....
.....

Certbot(認証更新コマンド)の実行スケジュール確認

PS > Get-ScheduledTaskInfo -TaskName "Certbot Renew Task"


LastRunTime        : 12/5/2022 4:16:16 PM
LastTaskResult     : 2147946720
NextRunTime        : 12/5/2022 11:42:42 PM
NumberOfMissedRuns : 0
TaskName           : certbot renew task
TaskPath           :
PSComputerName     :

ログイン時にコマンドプロンプト起動

PS > $Sta = New-ScheduledTaskAction -Execute "Cmd"
PS > $Stt = New-ScheduledTaskTrigger -AtLogon
PS > Register-ScheduledTask Task01 -Action $Sta -Trigger $Stt

schtasks コマンドによるスケジュール管理

システム起動時にアプリを起動

PS > schtasks /create /tn MyApp /tr c:\apps\myapp.exe /sc onstart

セキュリティ プリンシパルは、ユーザー アカウント、コンピューター アカウント、ユーザーまたはコンピューター アカウントのセキュリティ コンテキストで実行されるスレッドまたはプロセス、またはこれらのアカウントのセキュリティ グループなど、オペレーティング システムによって認証できる任意のエンティティです。 セキュリティ プリンシパルは、長い間、Windows コンピューター上のセキュリティ保護可能なリソースへのアクセスを制御するための基盤でした。 各セキュリティ プリンシパルは、オペレーティング システムで一意のセキュリティ識別子 (SID) によって表されます。

セキュリティ識別子は、セキュリティ プリンシパルまたはセキュリティ グループを一意に識別するために使用されます。 セキュリティ プリンシパルは、ユーザー アカウント、コンピューター アカウント、またはユーザーまたはコンピューター アカウントのセキュリティ コンテキストで実行されるスレッドまたはプロセスなど、オペレーティング システムによって認証できる任意のエンティティを表すことができます。

各アカウントまたはグループ、またはアカウントのセキュリティ コンテキストで実行される各プロセスには、Windows ドメイン コントローラーなどの機関によって発行される一意の SID があります。 SID はセキュリティ データベースに格納されます。 システムは、アカウントまたはグループの作成時に特定のアカウントまたはグループを識別する SID を生成します。 SID がユーザーまたはグループの一意の識別子として使用されている場合、別のユーザーまたはグループを識別するために SID を再度使用することはできません。

SIDの確認

PS > get-localuser -name hogehoge | select *

AccountExpires         :
Description            : Built-in account for administering the computer/domain
Enabled                : True
FullName               :
PasswordChangeableDate : 12/1/2022 6:14:24 AM
PasswordExpires        : 1/12/2023 6:14:24 AM
UserMayChangePassword  : True
PasswordRequired       : True
PasswordLastSet        : 12/1/2022 6:14:24 AM
LastLogon              : 12/6/2022 12:29:14 PM
Name                   : hogehoge
SID                    : S-1-5-21-xxxxxxxx-xxxxxxxxxx-xxxxxxxx-500
PrincipalSource        : Local
ObjectClass            : User

グループの確認

PS > whoami /groups

GROUP INFORMATION
-----------------

Group Name                                                    Type             SID          Attributes          
============================================================= ================ ============ ===============================================================
Everyone                                                      Well-known group S-1-1-0      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114    Mandatory group, Enabled by default, Enabled group
BUILTIN\Administrators                                        Alias            S-1-5-32-544 Mandatory group, Enabled by default, Enabled group, Group owner
BUILTIN\Users                                                 Alias            S-1-5-32-545 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\REMOTE INTERACTIVE LOGON                         Well-known group S-1-5-14     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\INTERACTIVE                                      Well-known group S-1-5-4      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users                              Well-known group S-1-5-11     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization                                Well-known group S-1-5-15     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account                                    Well-known group S-1-5-113    Mandatory group, Enabled by default, Enabled group
LOCAL                                                         Well-known group S-1-2-0      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication                              Well-known group S-1-5-64-10  Mandatory group, Enabled by default, Enabled group
Mandatory Label\High Mandatory Level                          Label            S-1-16-12288
SID Display name 説 明
S-1-5-domain-500 管理者 システム管理者のユーザー アカウント。 すべてのコンピューターにはローカル管理者アカウントがあり、すべてのドメインにはドメイン管理者アカウントがあります。管理者アカウントは、オペレーティング システムのインストール中に作成された最初のアカウントです。 アカウントを削除、無効化、またはロックアウトすることはできませんが、名前を変更することはできます。既定では、管理者アカウントは Administrators グループのメンバーであり、そのグループから削除することはできません。
S-1-5-32-544 管理者 組み込みグループ。 オペレーティング システムの初期インストール後、グループの唯一のメンバーは管理者アカウントです。 コンピューターがドメインに参加すると、Domain Admins グループが Administrators グループに追加されます。 サーバーがドメイン コントローラーになると、Enterprise Admins グループも Administrators グループに追加されます。

Nginx自動起動

Nginxをシステム起動時にスタートさせる方法として、タスクスケジューラによる方法と専用アプリ NSSM による方法が以下サイトに掲載されています。

これを参考に、起動時(オプション:停止時)のバッチファイルを作成し、これをタスクスケジューラでスケジュールタスクとして登録します。NSSMは今回採用しません。

Nginx起動バッチファイル

start.bat

@ECHO OFF
REM Start Nginx
tasklist /FI "IMAGENAME eq nginx.exe" 2>NUL | find /I /N "nginx.exe">NUL
IF NOT "%ERRORLEVEL%"=="0" (
   REM Nginx is NOT running, so start it
   c:
   cd \nginx
   start nginx.exe
   ECHO Nginx started.
) else (
   ECHO Nginx is already running.
)

Nginx停止バッチファイル(オプション)

stop.bat

@ECHO OFF
REM Stop Nginx
tasklist /FI "IMAGENAME eq nginx.exe" 2>NUL | find /I /N "nginx.exe">NUL
IF "%ERRORLEVEL%"=="0" (
   REM Nginx is currently running, so quit it
   c:
   cd \nginx
   nginx.exe -s quit
   ECHO Nginx quit issued.
) else (
   ECHO Nginx is not currently running.
)

schtask コマンドによるタスクスケジュール登録(動作確認済)

起動バッチファイル start.batnginx.exe と同じディレクトリに格納し schtask コマンドで登録します。

PS > schtasks /create /tn nginx-proxy /tr c:\nginx\start.bat /sc onstart /ru System

Register-ScheduledTask によるタスクスケジュール登録(動作確認中—>動作しない)

PS > $taskName = "Nginx Task"

PS > $action = New-ScheduledTaskAction -Execute '/nginx/start.bat'

PS > $trigger = New-ScheduledTaskTrigger -AtStartup 

PS > $adminsSID = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-544")
PS > $adminsGroupID = $adminsSID.Translate([System.Security.Principal.NTAccount]).Value
PS > $principal = New-ScheduledTaskPrincipal -GroupId $adminsGroupID -RunLevel Highest

PS > Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskName -Description "Execute Run Nginx at Startup on System" -Principal $principal