AzurePlaybook云计算自动化

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]

您是否遇到过尝试使用Azure服务主体对象和PowerShell脚本进行自动化作业的问题?
Have you ever encountered an issue where is trying to use service principle and PowerShell script for automation job?

在这里,我将在下面提供关于如何实现这一点的详细指南,在这个例子中,我将向您展示如何禁用特定功能(defender pricing plan)。您也可以将其用于其他的RestAPI请求。
Here I am going to provide the detailed guide below about how to achieve this, and in the example, I am going to show you how to disable defender pricing plan for all your resources. But you can always use it for other Rest API request.

[本文为AndyX.Net原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明!]

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图

[本文由Jack Tu撰写并授权AndyX.Net发布,本文的“Azure Portal”门户界面以英文为主,仅供参考。]

[本人中所有涉及到 Azure 的实验均在 Azure Global 国际版中进行配置,部分功能可能在 Azure 世纪互联中受到限制]

[本文为AndyX.Net原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明!]

 

先决条件(Prerequisite):

需要一台持续在线的Azure VM,可以是Windows也可以是Linux。
Need an online Azure VM, either Windows OS or Linux OS.

本教程仅提供思路,将以Windows+Azure Powshell为例,如有需要你可以创建Linux+Curl环境或者直接使用Azure自动化来实现相同的功能。
This tutorial just provides the concept, using Windows+Azure PowerShell as an example. If needed, you can create a Linux+Curl environment or directly use Azure Automation to achieve the same feature.

详细步骤(Step by step):

1.设置服务主体(Setup service principal):

首先,Azure REST API身份验证是通过身份验证头中的承载令牌完成的。因此我们需要“Azure服务主体”的令牌授权。
First, Azure REST API authentication is done via a Bearer token in the Authentication header. We’ll need a service principal to get that token for us.

通过Azure Cloud Shell验证您当前的订阅(如果安装了Azure CLI,则通过您的本地计算机验证):
Verify your current subscription via Cloud Shell (or your local computer if Azure CLI installed):

$ az account show --query id -o tsv
xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx

 

2. 创建自定义名称的Azure 服务主体:
Create a service principal with your specified name:

az ad sp create-for-rbac -n "restapitujack"                                                                                                                        
The output includes credentials that you must protect. Be sure that you do not include these credentials in your code or check the credentials into your source control. For more information, see https://aka.ms/azadsp-cli
{
  "appId": "25c317f9-9a3e-409c-xxxx-xxxxxxxxxxx",
  "displayName": "restapitujack",
  "password": "xxxtxx~xxx-xxxxxxxxxxxxxxxxxxx",
  "tenant": "72f988bf-86f1-xxxx-xxxxxxxxxxxx"
}

 

3. 为服务主体(AppId)分配“参与者”角色权限:
Assign the service principal (AppId) with “Contributor” role:

az role assignment create --assignee "25c317f9-9a3e-409c-xxxx-xxxxxxxxxx" --role "Contributor"                                                                   
--scope argument will become required for creating a role assignment in the breaking change release of the fall of 2023. Please explicitly specify --scope.
{
  "condition": null,
  "conditionVersion": null,
  "createdBy": null,
  "createdOn": "2023-08-09T13:54:24.089633+00:00",
  "delegatedManagedIdentityResourceId": null,
  "description": null,
  "id": "/subscriptions/xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/providers/Microsoft.Authorization/roleAssignments/8c405975-xxxx-xxxx-xxxx-xxxxxxxxxxx",
  "name": "8c405975-xxxx-xxxx-xxxx-xxxxxxxxxxx",
  "principalId": "6006227f-xxxx-xxxx-xxxx-xxxxxxxxxxx ",
  "principalType": "ServicePrincipal",
  "roleDefinitionId": "/subscriptions/xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/providers/Microsoft.Authorization/roleDefinitions/b24988ac-xxxx-xxxx-xxxx-xxxxxxxxxxx ",
  "scope": "/subscriptions/xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
  "type": "Microsoft.Authorization/roleAssignments",
  "updatedBy": "2812cec2-xxxx-xxxx-xxxx-dxxxxxxxxxx",
  "updatedOn": "2023-08-09T13:54:24.381627+00:00"
}
 

 

4. 从“订阅 -> IAM访问控制 -> 角色分配”中找到新创建的服务主体
We can find the new created service principal from Subscription -> IAM -> Role assignments:

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图1

5. 点击“服务主体”双重确认详细信息:
More details can be found by clicking the service principal (app):

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图2

6. 在Windows中安装Azure Powshell(Install Azure Powshell in Windows OS):

在您的计算机中安装Azure Powershell,允许VM访问Azure平台,以便在Azure上自动运行脚本。我们也可以通过Azure automation job将其作为自动化作业,但在本例中,我将选择普通vm以使其更易于理解。
Install Azure Powershell in your machine which have access to the Azure Platform, that on it you want to run the script automatically . It can be any windows, linux vm which installed the Powershell and Azure Powershell.
We can also make it an automation job via Azure Automation Job, but in this example, I will choose normal vm to make it easier to understand.

您可以参考文档了解如何安装Azure Powershell:如何安装 Azure PowerShell | Microsoft Learn
You can refer to the document for how to install Azure Powershell: How to install Azure PowerShell | Microsoft Learn

7. 详细的脚本如下所示(The detailed script shows below) :
(您需要在创建服务凭据时修改从上一步获得的订阅id、租户id、客户端id和客户端机密)
(You need to modify the subscription id, tenant id, client id, clientsecret in the below script that you get from the previous step when creating the service credential)

# Service Principal Credentials
$tenantId = "72f988bf-86f1-xxxx-xxxxxxxxxxxx"             
$clientId = "25c317f9-xxxx-xxxx-xxxx-xxxxxxxxxxx"
$clientSecret = "xxxtxx~xxx-xxxxxxxxxxxxxxxxxxx"
$subscriptionId = "xxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxx "
 
# Convert client secret to a secure string
$securePassword = ConvertTo-SecureString $clientSecret -AsPlainText -Force
 
# Create a PSCredential object using the client ID and secure password
$psCred = New-Object System.Management.Automation.PSCredential($clientId, $securePassword)
 
# Authenticate using Service Principal
Connect-AzAccount -ServicePrincipal -TenantId $tenantId -Credential $psCred -Subscription $subscriptionId
 
# API version
$apiVersion = "2023-01-01"
 
# Base URL for Azure Management API
$baseUrl = "https://management.azure.com"
 
# Array of API URLs for different resource types
$urls = "$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/SqlServers?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/SqlServerVirtualMachines?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/OpenSourceRelationalDatabases?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/CosmosDbs?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/CloudPosture?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/VirtualMachines?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/AppServices?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/StorageAccounts?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/Containers?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/KubernetesService?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/ContainerRegistry?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/KeyVaults?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/Arm?api-version=$apiVersion",
"$baseUrl/subscriptions/$SubscriptionId/providers/Microsoft.Security/pricings/Api?api-version=$apiVersion"
 
# Headers for API requests
$headers = @{
    "Authorization" = "Bearer $((Get-AzAccessToken -ResourceUrl $baseUrl).Token)"
    "Content-Type" = "application/json"
}

# New pricing plan details
$newpricingplan = @{
    "properties" = @{
        "pricingTier" = "Free"  # Change this to the desired SKU
    }
}
 
# Convert the pricing plan to JSON format
$body = $newpricingplan | ConvertTo-Json

# Loop through each URL and send API requests
Foreach ( $url in $urls ){
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Put -Body $body
$response
}

在修改了上述脚本中的各种id后,将该脚本保存为ps1文件。
After modifying the various id in the above script, then save the script as the ps1 file.

 

9. 在虚拟机中设置计划任务(Setup scheduled task in your vm):

您可以在windows或linux中运行该PS脚本,在我的示例中,使用“每日任务”来调度。
You can run the script in windows or linux, in my example I am using the windows vm to schedule the task every day.

登录到您的虚拟机,打开计划任务。Login to your , open the scheduled task.

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图3

10. 在“任务计划库”下创建文件夹“AzureTask”,点击“创建任务”;
Create Folder “AzureTask” under “Task Schedule Libary” and click “Create Task”;

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图4

11. 提供任务名称,按如下方式配置安全选项:
Provide the task name, configure the security options as below:

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图5

12. 转到第二个选项卡,为脚本配置“触发器”,在本例子中,我让它每天在指定的时间运行。
Go to the second tab, configure the “Trigger” for the script, In this example I make it run daily at the specified time.

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图6

设置操作,
Setup the actions:

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图7

然后可以将其他设置设置为默认设置。
Then other settings can be set as default.

设置计划任务后,您可以手动运行该任务,看看它是否有效。
After you setup the scheduled task, you can manually run the task to see if it works or not.

微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语]插图8

 

参考文献:

 

(END)

 

文章撰写:作者Jack Tu,来自Microsoft,已授权AndyX.Net发布。

文章遵循 CC 4.0 BY-SA 版权协议,若需转载本文,请标注来源与链接:原创内容AndyX.Net版权所有

本文链接:微软Azure云 LAB 101:Azure PS发送RestAPI请求并将其作为自动化作业[中英双语] – AndyX.Net – 安迪克斯

关联链接:微软Azure云 LAB 101: 使用Azure自动化作业定期执行特定任务的实验 – AndyX.Net – 安迪克斯