Как отредактировать Azure App Service с помощью Azure Python SDK? - PullRequest
0 голосов
/ 09 июля 2020

Я следую приведенному здесь примеру https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-example-web-app?tabs=cmd#4 -write-code-to-provision-and-deploy-a-web-app пытаюсь обновить существующую службу приложений с помощью Python SDK .

Вот мой код

from azure.mgmt.web import WebSiteManagementClient
from azure.common.client_factory import get_client_from_cli_profile
import os

def insert_access_restriction():
    rg_name = os.environ.get('RESOURCE_GROUP_NAME', None)
    location = os.environ.get('LOCATION', None)
    sp_name = os.environ.get('SERVICE_PLAN_NAME', None)
    web_app_name = os.environ.get('WEB_APP_NAME', None)
    sub_id = os.environ.get('AZURE_SUBSCRIPTION_ID', None)
    
    app_service_client = get_client_from_cli_profile(WebSiteManagementClient)
    poller = app_service_client.app_service_plans.create_or_update(rg_name,
        sp_name,
        {
            "location": location,
            "reserved": True,
            "sku" : {"name" : "S1"}
        }
    )
    plan_result = poller.result()
    
    poller = app_service_client.web_apps.create_or_update(rg_name,
        web_app_name,
        {
            "location": location,
            "server_farm_id": plan_result.id,
            "site_config": {
                "ip_restriction": {
                    "ip_address": "3.3.3.3/32"
                },
                "ip_restriction": {
                    "ip_address": "4.4.4.4/32"
                }                    
            }
        }
    )

Вызов этой функции app_service_client.app_service_plans.create_or_update возвращает

azure .mgmt.web.v2019_08_01.models. _models_py3.DefaultErrorResponseException: операция вернула недопустимый код состояния «Плохой запрос»

Мое местоположение centralus. Цель этой программы - обновить ограничения IP-адресов для существующей службы приложения программно из приложения-функции, когда новый список IP-адресов добавляется в контейнер хранения. Ошибка очень расплывчатая, как мне получить существующий план службы приложения, его службу приложения, а затем обновить службу приложения с помощью Python SDK?

1 Ответ

1 голос
/ 14 июля 2020

, если вы хотите обновить настройки ограничений IP для существующей службы приложения с помощью python sdk, обратитесь к следующему коду

  1. Создайте участника службы и назначьте Contributor sp
az login
# create sp and assign Contributor role to the sp at subscription level
az ad sp create-for-rbac -n "MyApp"
Код
client_id = 'your sp appId'
secret = 'your sp password'
tenant = 'your sp tenant'
credentials = ServicePrincipalCredentials(
        client_id = client_id,
        secret = secret,
        tenant = tenant
)

Subscription_Id = ''

web_client=WebSiteManagementClient(
    credentials,
    Subscription_Id
)
resorurce_group_name='your appservice group name'
name='you appservice name'

web_client.web_apps.create_or_update_configuration(resorurce_group_name, name,{

    'ip_security_restrictions':[

        {
            'ip_address': "0.0.0.0/0", 
            'action': "Allow", 
            'priority': 30, 
            'name': "test"
        }
    ]
})

enter image description here

for more details, please refer to здесь и здесь

# Обновить

Если вы хотите запустить сценарий в функции Azure, выполните следующие шаги.

  1. Создать Azure функцию

  2. Включить Azure MSI для Azure Функция enter image description here

  3. Assign role fro the MSI enter image description here enter image description here

  4. code (I use HTTP trigger to get web app configuration)

import logging
import pyodbc
import json
import azure.functions as func
from msrestazure.azure_active_directory import MSIAuthentication
from azure.mgmt.web import WebSiteManagementClient

async def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    
    creds =MSIAuthentication()
    Subscription_Id = 'e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68'
    group_name='0730BowmanWindowAndLinux2'
    name='413Bowman'

    web_client=WebSiteManagementClient(
        creds,
        Subscription_Id
    )
    result =web_client.web_apps.get_configuration(group_name, name,raw=True)
    return func.HttpResponse(json.dumps(result.response.json()))

...