MS Azure/AZ104

AZ104 실습 : Azure CLI 로 웹사이트 만들기

aliceintr 2021. 1. 8. 22:23
반응형

Azure Learning Path 에서 제공하는 Sandbox 기능으로 무료로 실습을 해보도록하자

Azure Learning Path :[MS Azure/AZ104] - AZ104 : Azure Administrator Associate 시험 소개

 

AZ104 : Azure Administrator Associate 시험 소개

이번 1월 달 목표는 AZ 104 와 AZ 400 을 동시에 따는 것이다. 일단. AZ 400 자격증을 따기 위해서는 선행으로 AZ104 or AZ204 시험을 패스해야 한다. 고로 이번주 부터 AZ 104 부터 차근차근 해보고자 한다.

buildgoodhabit.tistory.com

Azure CLI 시작하기 :[MS Azure/AZ104] - AZ104 실습 : Azure CLI 설치 및 사용 in MAC

 

AZ104 실습 : Azure CLI 설치 및 사용 in MAC

오늘은 가장 기본이 되는 Azure CLI Mac 용 설치 및 로그인을 해보도록 한다. 일단 터미널을 열고 brew update && brew install azure-cli Already up-to-date. ==> Downloading https://homebrew.bintray.com/bot..

buildgoodhabit.tistory.com


리소스 그룹 사용

 

이미 샌드박스에는 기본적으로 resource group 이 생성되어있고 이름은 learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0

이제 export cmd 로 필요한 value를 다 픽스해준다.

export RESOURCE_GROUP=learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0
export AZURE_REGION=centralus
export AZURE_APP_PLAN=popupappplan-$RANDOM
export AZURE_WEB_APP=popupwebapp-$RANDOM

$RANDOM은 꼭 숫자로 치환해서 쓴다. 예를 들면 popupwebapp-1234 이런식으로

이제 azure resource group 이 무엇이 있는지 테이블 구조로 보자

$ az group list --output table

Name                                        Location    Status
------------------------------------------  ----------  ---------
learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0  westus      Succeeded

query 문으로 필터해서 볼 수도 있다

$ az group list --query "[?name == '$RESOURCE_GROUP']"

[
  {
    "id": "/subscriptions/6c4f56a8-7f7a-42d2-b391-9bd89318901d/resourceGroups/learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0",
    "location": "westus",
    "managedBy": null,
    "name": "learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0",
    "properties": {
      "provisioningState": "Succeeded"
    },
    "tags": {
      "x-created-by": "freelearning",
      "x-created-for": "acb501a2-7e70-4fbe-82ab-1520d34a881f",
      "x-module-id": "learn.control-azure-services-with-cli"
    },
    "type": "Microsoft.Resources/resourceGroups"
  }
]

서비스 계획을 만드는 단계

Azure App Service를 사용하여 Web Apps를 실행하는 경우 앱에서 사용하는 Azure 컴퓨팅 리소스에 대한 요금이 청구되며, 리소스 비용은 Web Apps와 연결된 App Service 계획에 따라 달라집니다. 서비스 계획은 앱 데이터 센터에 사용되는 지역, 사용되는 VM 수 및 가격 책정 계층을 결정한다.

※ NOTE : 앱의 이름과 계획은 모든 Azure에서 고유 해야한다. 이전에 만든 변수는 임의의 값을 접미사로 할당하여 고유한 값을 유지합니다. 그러나 리소스를 만들 때 오류가 발생할 경우 이전에 나열된 명령을 실행하여 모든 변수를 새로운 임의의 값으로 재설정해야 한다..

리소스 그룹에 대한 오류가 표시되면 이전에 나열된 명령을 다른 리소스 그룹 값으로 실행한다.

1. 앱을 실행할 App Service 계획을 만든다. 다음 명령은 체험용 가격 책정 계층을 지정하지만 az appservice plan create --help를 실행하여 다른 가격 계층을 볼 수 있다.

az appservice plan create --name $AZURE_APP_PLAN --resource-group $RESOURCE_GROUP --location $AZURE_REGION --sku FREE
{- Finished ..
  "freeOfferExpirationTime": null,
  "geoRegion": "Central US",
  "hostingEnvironmentProfile": null,
  "hyperV": false,
  "id": "/subscriptions/6c4f56a8-7f7a-42d2-b391-9bd89318901d/resourceGroups/learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0/providers/Microsoft.Web/serverfarms/popupappplan-1234",
  "isSpot": false,
  "isXenon": false,
  "kind": "app",
  "location": "Central US",
  "maximumElasticWorkerCount": 1,
  "maximumNumberOfWorkers": 1,
  "name": "popupappplan-1234",
  "numberOfSites": 0,
  "perSiteScaling": false,
  "provisioningState": "Succeeded",
  "reserved": false,
  "resourceGroup": "learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0",
  "sku": {
    "capabilities": null,
    "capacity": 0,
    "family": "F",
    "locations": null,
    "name": "F1",
    "size": "F1",
    "skuCapacity": null,
    "tier": "Free"
  },
  "spotExpirationTime": null,
  "status": "Ready",
  "subscription": "6c4f56a8-7f7a-42d2-b391-9bd89318901d",
  "tags": null,
  "targetWorkerCount": 0,
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
}

2. 모든 계획을 표에 나열하여 서비스 계획이 성공적으로 생성되었는지 확인한다.

az appservice plan list --output table
Kind    Location    MaximumNumberOfWorkers    Name                NumberOfSites    ResourceGroup                               Status
------  ----------  ------------------------  ------------------  ---------------  ------------------------------------------  --------
app     Central US  3                         popupappplan-1234   0                Learn-12345678-1234-1234-1234-123456789abc  Ready

웹앱을 만드는 단계

이제 서비스 계획에 웹앱을 추가한다. . 코드를 동시에 배포할 수 있지만, 이 예제에서는 웹앱을 만들고 코드를 별도의 단계로 배포한다.

1. 웹앱을 만들려면 위에서 만든 앱 계획의 이름과 웹앱 이름을 입력한다. 앱 계획 이름과 마찬가지로 웹앱 이름도 고유해야 하며 이전에 만든 변수를 적용하면 된다.

az webapp create --name $AZURE_WEB_APP --resource-group $RESOURCE_GROUP --plan $AZURE_APP_PLAN
{- Finished ..
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "clientCertExclusionPaths": null,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "popupwebapp-5678.azurewebsites.net",
  "enabled": true,
  "enabledHostNames": [
    "popupwebapp-5678.azurewebsites.net",
    "popupwebapp-5678.scm.azurewebsites.net"
  ],
  "ftpPublishingUrl": "ftp://waws-prod-dm1-151.ftp.azurewebsites.windows.net/site/wwwroot",
  "hostNameSslStates": [
    {
      "hostType": "Standard",
      "ipBasedSslResult": null,
      "ipBasedSslState": "NotConfigured",
      "name": "popupwebapp-5678.azurewebsites.net",
      "sslState": "Disabled",
      "thumbprint": null,
      "toUpdate": null,
      "toUpdateIpBasedSsl": null,
      "virtualIp": null
    },
    {
      "hostType": "Repository",
      "ipBasedSslResult": null,
      "ipBasedSslState": "NotConfigured",
      "name": "popupwebapp-5678.scm.azurewebsites.net",
      "sslState": "Disabled",
      "thumbprint": null,
      "toUpdate": null,
      "toUpdateIpBasedSsl": null,
      "virtualIp": null
    }
  ],
  "hostNames": [
    "popupwebapp-5678.azurewebsites.net"
  ],
  "hostNamesDisabled": false,
  "hostingEnvironmentProfile": null,
  "httpsOnly": false,
  "hyperV": false,
  "id": "/subscriptions/6c4f56a8-7f7a-42d2-b391-9bd89318901d/resourceGroups/learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0/providers/Microsoft.Web/sites/popupwebapp-5678",
  "identity": null,
  "inProgressOperationId": null,
  "isDefaultContainer": null,
  "isXenon": false,
  "kind": "app",
  "lastModifiedTimeUtc": "2021-01-08T13:05:45.830000",
  "location": "Central US",
  "maxNumberOfWorkers": null,
  "name": "popupwebapp-5678",
  "outboundIpAddresses": "13.89.172.2,23.99.133.160,23.101.117.42,23.101.112.78,23.99.229.34",
  "possibleOutboundIpAddresses": "13.89.172.2,23.99.133.160,23.101.117.42,23.101.112.78,23.99.229.34,168.61.189.180,168.61.214.234,23.99.231.53",
  "redundancyMode": "None",
  "repositorySiteName": "popupwebapp-5678",
  "reserved": false,
  "resourceGroup": "learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0",
  "scmSiteAlsoStopped": false,
  "serverFarmId": "/subscriptions/6c4f56a8-7f7a-42d2-b391-9bd89318901d/resourceGroups/learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0/providers/Microsoft.Web/serverfarms/popupappplan-5678",
  "siteConfig": {
    "acrUseManagedIdentityCreds": false,
    "acrUserManagedIdentityId": null,
    "alwaysOn": null,
    "apiDefinition": null,
    "apiManagementConfig": null,
    "appCommandLine": null,
    "appSettings": null,
    "autoHealEnabled": null,
    "autoHealRules": null,
    "autoSwapSlotName": null,
    "azureMonitorLogCategories": null,
    "azureStorageAccounts": null,
    "connectionStrings": null,
    "cors": null,
    "customAppPoolIdentityAdminState": null,
    "customAppPoolIdentityTenantState": null,
    "defaultDocuments": null,
    "detailedErrorLoggingEnabled": null,
    "documentRoot": null,
    "experiments": null,
    "fileChangeAuditEnabled": null,
    "ftpsState": null,
    "functionAppScaleLimit": null,
    "functionsRuntimeScaleMonitoringEnabled": null,
    "handlerMappings": null,
    "healthCheckPath": null,
    "http20Enabled": null,
    "httpLoggingEnabled": null,
    "ipSecurityRestrictions": [
      {
        "action": "Allow",
        "description": "Allow all access",
        "ipAddress": "Any",
        "name": "Allow all",
        "priority": 1,
        "subnetMask": null,
        "subnetTrafficTag": null,
        "tag": null,
        "vnetSubnetResourceId": null,
        "vnetTrafficTag": null
      }
    ],
    "javaContainer": null,
    "javaContainerVersion": null,
    "javaVersion": null,
    "limits": null,
    "linuxFxVersion": null,
    "loadBalancing": null,
    "localMySqlEnabled": null,
    "logsDirectorySizeLimit": null,
    "machineKey": null,
    "managedPipelineMode": null,
    "managedServiceIdentityId": null,
    "metadata": null,
    "minTlsVersion": null,
    "minimumElasticInstanceCount": 0,
    "netFrameworkVersion": null,
    "nodeVersion": null,
    "numberOfWorkers": null,
    "phpVersion": null,
    "powerShellVersion": null,
    "preWarmedInstanceCount": null,
    "publishingPassword": null,
    "publishingUsername": null,
    "push": null,
    "pythonVersion": null,
    "remoteDebuggingEnabled": null,
    "remoteDebuggingVersion": null,
    "requestTracingEnabled": null,
    "requestTracingExpirationTime": null,
    "routingRules": null,
    "runtimeADUser": null,
    "runtimeADUserPassword": null,
    "scmIpSecurityRestrictions": [
      {
        "action": "Allow",
        "description": "Allow all access",
        "ipAddress": "Any",
        "name": "Allow all",
        "priority": 1,
        "subnetMask": null,
        "subnetTrafficTag": null,
        "tag": null,
        "vnetSubnetResourceId": null,
        "vnetTrafficTag": null
      }
    ],
    "scmIpSecurityRestrictionsUseMain": null,
    "scmMinTlsVersion": null,
    "scmType": null,
    "tracingOptions": null,
    "use32BitWorkerProcess": null,
    "virtualApplications": null,
    "vnetName": null,
    "vnetPrivatePortsCount": null,
    "vnetRouteAllEnabled": null,
    "webSocketsEnabled": null,
    "websiteTimeZone": null,
    "winAuthAdminState": null,
    "winAuthTenantState": null,
    "windowsFxVersion": null,
    "xManagedServiceIdentityId": null
  },
  "slotSwapStatus": null,
  "state": "Running",
  "suspendedTill": null,
  "tags": null,
  "targetSwapSlot": null,
  "trafficManagerHostNames": null,
  "type": "Microsoft.Web/sites",
  "usageState": "Normal"
}

2. 앱을 표에 나열하여 앱이 성공적으로 생성되었는지 확인

% az webapp list --output table

Name               Location    State    ResourceGroup                               DefaultHostName                      AppServicePlan
-----------------  ----------  -------  ------------------------------------------  -----------------------------------  ------------------
popupwebapp-5678   Central US  Running  Learn-12345678-1234-1234-1234-123456789abc  popupwebapp-12345.azurewebsites.net  popupappplan-54321

표에 나열된 DefaultHostName 을 기억하자. 이는 새 웹 사이트에 연결할 수 있는 웹 주소이다.. Azure는 azurewebsites.net 도메인에서 고유한 앱 이름을 통해 웹 사이트를 사용할 수 있게 합니다. 예를 들어 앱 이름이 “popupwebapp-mslearn123”인 경우 웹 사이트 URL은 http://popupwebapp-mslearn123.azurewebsites.net 이다.

3. 사이트에는 브라우저 또는 CURL에서 확인할 수 있는 Azure에서 생성한 "빠른 시작" 페이지가 있으므로 DefaultHostName 을 사용한다. 이제 반환된 샘플 앱의 기본 HTML 확인이 가능하다.

$ curl $AZURE_WEB_APP.azurewebsites.net
<!DOCTYPE html>
 <html lang="en">
 <head> 
   <meta charset="utf8"> 
   <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
   <meta http-equiv=X-UA-Compatible content="IE=edge"> 
   <title>Microsoft Azure App Service - Welcome</title> 
   <link rel="shortcut icon" href="https://appservice.azureedge.net/images/app-service/v3/favicon.ico" type="image/x-icon"/> 
   <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/4.1.1/css/bootstrap.min.css" crossorigin="anonymous"> 
   <link rel="stylesheet" type="text/css" href="https://appservice.azureedge.net/css/app-service/v3/main.css"> 
   <script src="https://appservice.azureedge.net/scripts/app-service/v3/loc.min.js" crossorigin="anonymous">
   </script>
   <script type="text/javascript">
   		window.onload=function (){
        	try{var a=window.location.hostname; 
            if (a.includes(".azurewebsites.net")){
            	a=a.replace(".azurewebsites.net", "")
             }
             var b=document.getElementById("depCenterLink1"); 
             b.setAttribute("href", b.getAttribute("href") + "&sitename=" + a); 
             loc();}catch (d){}}
    </script>
</head>
<body> 
	<nav class="navbar navbar-light bg-light"> 
    <div class="navbar-brand "> 
    	<div class="container pl-4 ml-5"> 
        	<img src="https://appservice.azureedge.net/images/app-service/v3/microsoft_azure_logo.svg" width="270" height="108" alt=""> 
        </div>
    </div>
    </nav> 
   <div class="container-fluid container-height mr-2"> 
   		<div class="pt-10 pb-10 mt-10 mb-10 d-xxs-none d-xs-noned-sm-none d-md-none d-lg-block d-xl-block" style="height:20px; width:100%; clear:both;">
        </div>
        <div class="row"> 
        	<div class="row col-xs-12 col-sm-12 d-block d-lg-none d-xl-none d-md-block d-sm-block d-xs-block"> 
        		<div class="text-center"> 
        			<img src="https://appservice.azureedge.net/images/app-service/v3/generic.svg"> 
       			</div>
            </div>
       <div class=" extra-pl-small-scr offset-xl-1 offset-lg-1 offset-md-2 offset-sm-2 offset-xs-4 col-xl-5 col-lg-5 col-md-10 col-sm-11 col-xs-11 div-vertical-center"> 
       <div class="container-fluid"> 
       		<div class="row"> 
            		<h2 id="heyDevelopers">Hey, App Service developers!</h2> 
            </div><br>
            <div class="row"> 
            		<h4 id="upRunning">Your app service is up and running.</h4> 
            </div>
            <div class="row"> 
            		<h4 id="nextSteps">Time to take the next step and deploy your code.</h4> </div><div class="row info-mg-top"> <p class=" pl-0 col-md-6 col-sm-12 info-mg-top"><spanid="codeReady">Have your code ready?</span><br><span id="useDCenter"> Use deployment center to get code published from your client or setup continuous deployment.</span><br><a id="depCenterLink1" href="https://go.microsoft.com/fwlink/?linkid=2057852"><button class="btn btn-primary btn-mg-top" type="submit" id="deplCenter">Deployment Center</button></a></p><p class="pl-0 offset-md-1 col-md-5 col-sm-12 info-mg-top"> <span id="codeNotReady">Don't have your code yet?</span><br><span id="followQS">Follow our quickstart guide and you'll have a full app ready in 5 minutes or less.</span> <br><a href="https://go.microsoft.com/fwlink/?linkid=2084231"><button class="btn btn-primary btn-mg-top" type="submit" id="quickStart">Quickstart</button></a></p></div></div></div><div class="col-xl-5 col-lg-5 col-md-12 d-none d-lg-block"> 
   <div class="text-center">
      <img src="https://appservice.azureedge.net/images/app-service/v3/generic.svg"> 
   </div>
   </div>
   <div class="col-xl-1 col-lg-1 col-md-1">
   </div>
   </div>
   </div>
   <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.2.1.min.js" crossorigin="anonymous"></script> <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/4.1.1/bootstrap.min.js" crossorigin="anonymous"></script></body>
 </html>

 


GitHub에서 코드를 배포하는 단계

1. 최종 단계는 GitHu 에 웹앱으로 코드를 배포하는 것이다. 실행 시 “Hello World!”를 표시하는 Azure 샘플 GitHub 리포지토리에서 사용 가능한 간단한 PHP 페이지를 사용하는 예제이다. 위에서 만든 web app 이름을 사용한다.

az webapp deployment source config --name $AZURE_WEB_APP --resource-group $RESOURCE_GROUP --repo-url "https://github.com/Azure-Samples/php-docs-hello-world" --branch master --manual-integration 
{- Finished ..
  "branch": "master",
  "deploymentRollbackEnabled": false,
  "id": "/subscriptions/6c4f56a8-7f7a-42d2-b391-9bd89318901d/resourceGroups/learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0/providers/Microsoft.Web/sites/popupwebapp-5678/sourcecontrols/web",
  "isManualIntegration": true,
  "isMercurial": false,
  "kind": null,
  "location": "Central US",
  "name": "popupwebapp-5678",
  "repoUrl": "https://github.com/Azure-Samples/php-docs-hello-world",
  "resourceGroup": "learn-f47067a8-28f2-4e36-ac40-d41c8fd41db0",
  "type": "Microsoft.Web/sites/sourcecontrols"
}

2. 배포되면 브라우저 또는 CURL을 사용하여 사이트를 접속한다.

curl $AZURE_WEB_APP.azurewebsites.net 
Hello World!

 

이렇게 오늘 실습도 끄읕!

 

내용이 도움이 되셨다면 블로그 구독하기 부탁드리겠습니다.

* 이 글의 모든 저작권은 aliceintr에 있으며 무단 배포 및 사용은 자제해 주시기 바랍니다. *

반응형