programing

Azure PowerShell을 사용하여 기존 Azure 웹 애플리케이션에 앱 설정 추가

lastcode 2023. 4. 27. 22:29
반응형

Azure PowerShell을 사용하여 기존 Azure 웹 애플리케이션에 앱 설정 추가

웹 응용 프로그램 구성 추가를 자동화하기 위해 zure power shell을 사용하여 실행되는 스크립트를 작성하려고 합니다.

Azure > MyWebApp > Application Settings > App Settings

키 = "값"처럼 보입니다.

나는 이 대본을 씁니다.

###########################
# MyApp Config Automation #
###########################

#Begin

$subscriptionName="MySubscriptionName"
$webSiteName="MyWebAppName"
$storageAccountName="StorageAccountName"
########################################
$userName = "myaccount@outlook.com"
$securePassword = ConvertTo-SecureString -String "mypass" -AsPlainText -Force
#####################################
$cred = New-Object System.Management.Automation.PSCredential($userName, $securePassword)
#####################################
Add-AzureAccount -Credential $cred 
Select-AzureSubscription -SubscriptionName $subscriptionName -Default
#####################################
Get-AzureWebsite -Name $webSiteName

#End

하지만 위의 스크립트는 나의 웹 애플리케이션만 가져오는 것이라는 것을 알고 있습니다. 이제 나는 나의 웹 애플리케이션 > 애플리케이션 설정 > 앱 설정에 액세스하고 내 새로운 앱 설정의 스크립트 파일/어레이와 스크립트 검사를 제공해야 합니다. 만약 새로운 앱 설정 키가 있다면, 그것은 그것의 값을 재정의할 것입니다.단계 또는 APIS는 무엇입니까? 아니면 순수 파워 셸로 할 수 있습니까?

편집: 이 스크립트는 새 웹 응용 프로그램을 만들고 앱 설정을 자동으로 추가할 수 있습니다.

##############################################
# Creating website and Adding Configs Script #
##############################################

$webSiteName="mywebsite"
$storageAccountName="storageaccount"
$subscriptionName="mysubsc"
$userName = "myaccount"
$securePassword = ConvertTo-SecureString -String "mypass" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $securePassword)
Add-AzureAccount -Credential $cred 
Select-AzureSubscription -SubscriptionName $subscriptionName -Default

New-AzureWebsite -Name $webSiteName
New-AzureStorageAccount –StorageAccountName $storageAccountName -Location "South Central US"
$ClientId="dfgdf6"
$Password="ffefe"
$StorageAccountKey = Get-AzureStorageKey -StorageAccountName $storageAccountName
$AppSettings = @{"StorageAccountPrimary" = $StorageAccountKey.Primary;"StorageAccountSecondary" = $StorageAccountKey.Secondary;"ida:ClientId"=$ClientId;"ida:Password"=$Password}

Set-AzureWebsite -Name $webSiteName -AppSettings $AppSettings

다음은 2015년 12월 12일 Azure PowerShell 명령을 기반으로 한 업데이트입니다.예는 슬롯별 설정에 대한 것입니다. 전역을 원하는 경우 Get/Set-AzureRmWebApp을 사용하고 -slot 매개 변수를 제거합니다.

$myResourceGroup = 'PartsUnlimitedMRP'
$mySite = 'centpartsunlimited'

$webApp = Get-AzureRMWebAppSlot -ResourceGroupName $myResourceGroup -Name $mySite -Slot production
$appSettingList = $webApp.SiteConfig.AppSettings

$hash = @{}
ForEach ($kvp in $appSettingList) {
    $hash[$kvp.Name] = $kvp.Value
}

$hash['NewKey'] = "NewValue"
$hash['ExistingKey'] = "NewValue"

Set-AzureRMWebAppSlot -ResourceGroupName $myResourceGroup -Name $mySite -AppSettings $hash -Slot production

앱 설정 검색

먼저 이 두 변수를 설정합니다.

$myResourceGroup = 'RESOURCE_GROUP_NAME'
$mySite = 'SITE_NAME'

그런 다음 새 리소스 관리자 모드로 전환하고 계정에 로그인합니다.

Switch-AzureMode AzureResourceManager
Get-AzureAccount

그런 다음 앱 설정을 검색합니다.(뒤쪽 눈금(')은 새 줄을 의미합니다.)

(Invoke-AzureResourceAction -ResourceGroupName $myResourceGroup `
 -ResourceType Microsoft.Web/sites/Config -Name $mySite/appsettings `
 -Action list -ApiVersion 2015-08-01 -Force).Properties

앱 설정 추가/업데이트

설정을 업데이트하려면 먼저 설정을 변수에 넣습니다.

$props = (Invoke-AzureResourceAction -ResourceGroupName $myResourceGroup `
 -ResourceType Microsoft.Web/sites/Config -Name $mySite/appsettings `
 -Action list -ApiVersion 2015-08-01 -Force).Properties

사용하기Set-AzureWebsite변수를 해시 테이블로 변환합니다.

 $hash = @{}
 $props | Get-Member -MemberType NoteProperty | % { $hash[$_.Name] = $props.($_.Name) }

이제 해시 테이블에 값을 추가/업데이트합니다.

$hash.NewKey = "NewValue"
$hash.ExistingKey = "NewValue"

그런 다음 서비스 관리 모드로 다시 전환하고 설정을 커밋합니다.

Switch-AzureMode AzureServiceManagement
Set-AzureWebsite -Name $mySite -AppSettings $hash

전체 코드 목록

$myResourceGroup = 'RESOURCE_GROUP_NAME'
$mySite = 'SITE_NAME'

Switch-AzureMode AzureResourceManager
Get-AzureAccount

(Invoke-AzureResourceAction -ResourceGroupName $myResourceGroup `
 -ResourceType Microsoft.Web/sites/Config -Name $mySite/appsettings `
 -Action list -ApiVersion 2015-08-01 -Force).Properties

$props = (Invoke-AzureResourceAction -ResourceGroupName $myResourceGroup `
 -ResourceType Microsoft.Web/sites/Config -Name $mySite/appsettings `
 -Action list -ApiVersion 2015-08-01 -Force).Properties

 $hash = @{}
 $props | Get-Member -MemberType NoteProperty | % { $hash[$_.Name] = $props.($_.Name) }

$hash.NewKey = "NewValue"
$hash.ExistingKey = "NewValue"

Switch-AzureMode AzureServiceManagement
Set-AzureWebsite -Name $mySite -AppSettings $hash

메모들

Azure Service Management와 Azure Resource Manager는 동일한 세션에서 사용할 수 없습니다.현재로서는 후자가 다음을 통해 앱 설정을 업데이트하는 것을 허용하지 않는 것 같습니다.Set-AzureResource위의 내용은 해결 방법입니다.다른 방법은 PowerShell 대신 Azure CLI를 사용하는 것입니다.

이 답변들은 원래의 Azure PowerShell과 Azure RM이 모두 사용되지 않기 때문에 그들의 나이를 보여줍니다.Az PowerShell 모듈을 사용하여 이 작업을 수행하려면 다음과 같습니다.

Connect-AzAccount
$site = Get-AzWebApp -Name foo-com-dev-as
$oldSettings = ($site.SiteConfig.AppSettings | % { $h = @{} } { $h[$_.Name] = $_.Value } { $h })

$newSettings = @{ StorageAccountPrimary = $StorageAccountKey.Primary
                  StorageAccountSecondary = $StorageAccountKey.Secondary
                  "ida:ClientId" = $ClientId
                  "ida:Password" = $Password }

Set-AzWebApp -ResourceGroupName foo-com-dev-rg -Name foo-com-dev-as -AppSettings ($oldSettings + $newSettings)

설명.

  1. Connection-AzAccountAzure 계정에 연결합니다. 구독을 선택해야 하는 경우 다음 단계를 수행해야 할 수 있습니다.
  2. $site = Get-AzWebApp- 수정할 사이트를 검색합니다.
  3. $oldSettings- 기존의 모든 설정을 가져와 HashTable에 넣습니다.
    1. $site.SiteConfig.AppSettings | %과▁of통and▁a▁shorth▁pipes▁(▁via다▁setting니espass합▁each)▁alias의 단축 별칭을 통해 파이프(통과)합니다.ForEach-Object
    2. { $h = @{} }를 생성합니다.HashTable유로를 -Begin parameter 변수 개위
    3. { $h[$_.Name] = $_Value } 있는 을 에명값추니다에 합니다.HashTable 값에대의 각 값에 $site.SiteConfig.AppSettings유로를 -Process parameter 변수 개위
    4. { $h }된 새로채항반환합다니을목워진을 합니다.HashTable유로를 -End를 사용합니다.
  4. $newSettings = @{를 만듭니다.HashTable
  5. Set-AzWebApp- 두 개의 HashTables를 결합하고 기존 AppSettings를 결합된 집합으로 바꿉니다.이 경우 이전 설정과 새 설정 간에 중복이 없는 것으로 가정합니다.이러한 상황이 적용되는 경우에는 덮어쓰기/덮어쓰기 안 함과 같은 적절한 방식으로 중복제거가 필요합니다.

2023년 업데이트

여기에는 @robb-vandaver와 유사하지만 키가 겹치면 새 설정을 이전 설정으로 덮어쓰는 유틸리티 기능이 있습니다.순서를 바꾸기만 하면 역방향 동작을 얻을 수 있습니다.foreach진술들.

참고, 이미 Azure에 연결되어 있다고 가정합니다.

function Update-WebAppSettings {
    Param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$ResourceGroupName,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$AppName,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [hashtable]$AdditionalAppSettings
    )

    #common parameters to target the app in the resource group
    $WebAppSelection = @{
        ResourceGroupName = $ResourceGroupName
        Name              = $AppName
    }

    # hashtable where we will build up the complete merged set of app settings
    $NewAppSettings = @{}

    # get the old settings
    $CurrentAppSettingList = $(Get-AzWebApp @WebAppSelection).SiteConfig.AppSettings

    # they are in list format, so iterate through and add 
    # them to the hashtable we are building
    foreach ($Setting in $CurrentAppSettingList) {
        $NewAppSettings[$Setting.Name] = $Setting.Value
    }

    # iterate through the new settings hashtable and add them to the one we are building
    # NB: if new settings have the same keys as old settings it will overwrite them (this 
    # is different behavior than if you merge the two hashtables with the '+' operator)
    foreach ($Key in $AdditionalAppSettings.Keys) {
        $NewAppSettings[$Key] = $AdditionalAppSettings[$Key]
    }

    $WebAppSettings = @{
        AppSettings       = $NewAppSettings
    }

    Set-AzWebApp @WebAppSelection @WebAppSettings
}

상담 사이트에서 다음을 수행합니다.

$AdditionalAppSettings = @{
    someSetting = "someValue"
    someOtherSetting = "someOtherValue"
}
Update-WebAppSettings -ResourceGroupName my-resource-group -AppName myWebServicesApp -AdditionalAppSettings @AdditionalAppSettings

언급URL : https://stackoverflow.com/questions/32543778/adding-an-app-settings-to-existing-azure-web-application-using-azure-power-shell

반응형