LoginSignup
0
0

More than 3 years have passed since last update.

powershell: パスワードベースの非対話な Azure へのログイン

Last updated at Posted at 2019-08-05

本記事では、AzureRM (Az) モジュールをインストールした PowerShell 環境で、対話的なログイン画面を表示させずに、パスワード ベースで Azure にログインするスクリプトを紹介します。

以下のスクリプトでは AzureRm を利用していますが、Az でもコマンド名が変わるだけで手順は全く同様です。
各コマンドの AzureRm を Az に置換すればそのまま使うことが出来ます。

Powershell ログイン用のアカウントを作成

このステップでは urlpass の二つのパラメータを対話的に与えます。

  • url: アプリを一意に識別するのに使われる、ホームページの URL。適当に作成して構わない (e.g. http://openjny.oracle.com)。
  • pass: パスワード。16 字以上の半角文字からなる文字列で、1 文字以上の記号/大文字/小文字を含む。
# Login
Login-AzureRmAccount

# Select subscription
Get-AzureRmSubscription | Out-GridView -PassThru | Set-AzureRmContext

# Create an app for logging-in on powershell
$url = Read-Host "Enter app url (begins with http)"
$pass = Read-Host "Enter password (must be at least 16 characters long)" -AsSecureString

$app = New-AzureRmADApplication `
    -DisplayName "PowerShellLogin" `
    -HomePage $("{0}/PowerShellLogin" -f $url) `
    -IdentifierUris $("{0}/PowerShellLogin" -f $url) `
    -Password $pass
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $app.ApplicationId

# Output information for login
"Tennant ID:" + (Get-AzureRmTenant).Id | Write-Output
"App ID:" + $app.ApplicationId | Write-Output

入力に与えたパスワード、及び最終的に出力されるテナント ID と App ID の 3 つの情報がログイン時に必要となります。
これらの情報は、安全な場所に保存して置いて下さい。

ログイン時

以下の 3 つの情報をパラメータとして与えます。

  • tenantId: テナント ID
  • username: App ID
  • password: パスワード

セキュリティの観点からは、これらの値のハードコーディングは推奨されません。
適宜、環境変数から読み取るなどの対策を施して下さい。

$tenantId = "<Tenant ID>"
$username = "<App ID>"
$password = ConvertTo-SecureString "<Password>" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
Login-AzureRmAccount -Credential $cred -ServicePrincipal -Tenant $tenantId
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