文章:使用 PowerShell 非交互式登录 Azure





0/5 (0投票)
如何使用 PowerShell 非交互式登录 Azure
创建服务主体
你肯定不希望在脚本中包含你的个人登录凭据。你需要一个服务帐户,它只具有运行脚本所需的最低权限。
这通过服务主体来实现,服务主体是你在 Active Directory 上的应用程序的一个实例,你授予其访问资源的权限。
1. 使用以下命令登录到你的 Azure 帐户:
Login-AzureRmAccount
2. 然后我们需要创建一个 Active Directory 应用程序。
$displayName = "App Display Name"
$homePage = "http://YourApplicationHomePage"
$identifierUris = "http://YourApplicationUri"
$password = "APasswordHere"
$app = New-AzureRmADApplication –DisplayName $displayName
–HomePage $homePage –IdentifierUris $identifierUris –Password $password
3. 创建服务主体。
现在我们需要为该应用程序创建一个服务主体,该服务主体需要访问资源。这需要使用我们上面创建的应用程序的 applicationId
。
New-AzureRmADServicePrincipal –ApplicationId $app.ApplicationId
4. 授予服务主体角色。
你可以在此链接查看默认角色的列表。
New-AzureRmRoleAssignment –RoleDefinitionName Contributor
–ServicePrincipalName $app.ApplicationId
使用服务主体进行身份验证
1. 创建 PSCredential 对象
$username = "YourUserName"
$pass = ConvertTo-SecureString "YourPassword" -AsPlainText –Force
$cred = New-Object -TypeName pscredential –ArgumentList $username, $pass
2. 从你的订阅中获取 TenantId
$tenant = (Get-AzureRmSubscription).TenantId
使用凭据对象登录
Login-AzureRmAccount -Credential $cred -ServicePrincipal –TenantId $tenant
保存令牌以便稍后登录
你可以将配置文件保存为令牌,并使用该令牌稍后登录。但是,这会过期,通常持续约 12 小时。
Save-AzureRmProfile -Path c:\AzureLoginToken.json
下次要登录时,只需加载配置文件即可。
Select-AzureRmProfile -Path c:\AzureLoginToken.json
使用服务主体和证书进行身份验证
这与上述内容非常相似,只是我们首先必须生成要使用的证书,然后使用该证书创建 AD 应用程序。
1. 登录到 Azure
Login-AzureRmAccount
2. 创建证书
$cert = New-SelfSignedCertificate -CertStoreLocation "cert:\CurrentUser\My"
-Subject "CN=exampleapp" -KeySpec KeyExchange
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
3. 创建 AD 应用程序
$azureAdApplication = New-AzureRmADApplication -DisplayName "exampleapp"
-HomePage "https://www.contoso.org"
-IdentifierUris "https://www.contoso.org/example"
-KeyValue $keyValue -KeyType AsymmetricX509Cert
-EndDate $cert.NotAfter -StartDate $cert.NotBefore
4. 创建服务主体
New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
5. 将角色分配给服务主体
New-AzureRmRoleAssignment -RoleDefinitionName Contributor
-ServicePrincipalName $azureAdApplication.ApplicationId.Guid
创建证书登录脚本
1. 获取应用程序 ID
$applicationId = $azureAdApplication.ApplicationId
# Alternatively
# $applicationId = (Get-AzureRmADApplication
-IdentifierUri "https://www.yourappURL.com").ApplicationId
2. 获取证书的指纹
$thumbprint = $cert.Thumbprint
# Alternatively
# $thumbprint = (Get-ChildItem -Path cert:\CurrentUser\My\* -DnsName exampleapp).Thumbprint
3. 获取租户
$tenantId = (Get-AzureRmSubscription).TenantId
4. 保存名为 login.ps1 的文件
此脚本是你要使用的登录脚本,它包含登录为新创建的服务主体所需的指纹、applicationId 和 tenantId。
$loginCommand = "Add-AzureRmAccount -ServicePrincipal -CertificateThumbprint $thumbprint
-ApplicationId $applicationId -TenantId $tenantId"
Add-Content <span class="s1">'c:\login.ps1' $loginCommand
总结
希望这为你提供了一些选项,并介绍了如何非交互式登录到 Azure。
脚本示例在 GitHub 上。