Windows 환경의 PowerShell에서 Ncloud API를 호출하는 샘플 예제입니다

개요

네이버 클라우드 인프라와 상품 및 솔루션 등의 활용을 도와주는 API를 Windows PowerShell에서 호출하는 샘플 예제를 정리해봅니다.
네이버 클라우드 API는 RESTful API 방식으로 제공되며, XML와 JSON 형식으로 응답합니다 우선 전체 소스코드를 살펴보고 다음으로 주요 코드를 상세하게 살펴보겠습니다.

API 호출 샘플 코드

function Sign-Request(
    [string] $api_server,
    [string] $api_url,         
    [string] $apicall_method,      
    [string] $ncloud_accesskey,  
    [string] $ncloud_secretkey 
)
{   
    $unixtimestamp = [DateTimeOffset]::Now.ToUnixTimeSeconds() * 1000
    
    $space = " "
    $new_line = "`n"
 
    $message = $apicall_method + $space +
                $api_url + $new_line +
                $unixtimestamp + $new_line +
                $ncloud_accesskey                    

    $signature = Compute-HMACSHA256Hash $ncloud_secretkey $message
    
    # Return request headers
    return @{
        "x-ncp-apigw-timestamp" = $unixtimestamp;
        "x-ncp-iam-access-key" = $ncloud_accesskey;
        "x-ncp-apigw-signature-v2" = $signature
    }
}

function Compute-HMACSHA256Hash(
    [string] $secret,      # base64 encoded
    [string] $content
)
{
    $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
    try {
        $hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret)
        $signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($message))   
        
        return [Convert]::ToBase64String($signature)
    }
    finally {
        $hmacsha.Dispose()
    }
}

# API 서버와 URL 예시 : 상품별 가격 리스트 호출 api
$api_server = "https://billingapi.apigw.ntruss.com";
$api_url = "/billing/v1/product/getProductPriceList";
$api_url = $api_url + "?regionCode=KR&productItemKindCode=VSVR";

$apicall_method = "GET"
$body = $null
$ncloud_accesskey = "Ncloud AccessKey"
$ncloud_secretkey = "Ncloud SecretKey"
$api_full_url = $api_server + $api_url

$headers = Sign-Request $api_server $api_url $apicall_method $ncloud_accesskey $ncloud_secretkey

Invoke-WebRequest -Uri $api_full_url -Method $apicall_method -Headers $headers  -Body $body

코드 상세 설명

유닉스 타임 스탬프

$unixtimestamp = [DateTimeOffset]::Now.ToUnixTimeSeconds() * 1000

네이버 클라우드 API를 호출할 때는 13자리 형식의 유닉스 타임 스탬프가 필요합니다.
계산한 날짜 값에 1000을 곱해서 13자리로 만듭니다.

hmac으로 암호화할 문자열 설정

암호화할 문자열을 설정하는데 필요한 값을 사전에 정의합니다.

$space = " "
$new_line = "`n"

$message = $apicall_method + $space +
            $api_url + $new_line +
            $unixtimestamp + $new_line +
            $ncloud_accesskey	

네이버 클라우드 API에서는 호출 방식(GET, POST)과 도메인을 제외한 API URL, 유닉스 타임스탬프, API ACCESSKEY를 공백과 개행문자 `n을 이용해서 하나의 문자열로 설정합니다.

hmac_sha256 방식으로 암호화

$signature = Compute-HMACSHA256Hash $ncloud_secretkey $message

function Compute-HMACSHA256Hash(
    [string] $secret,      # base64 encoded
    [string] $content
)
{
    $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
    try {
        $hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret)
        $signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($message))   
        
        return [Convert]::ToBase64String($signature)
    }
    finally {
        $hmacsha.Dispose()
    }
}

hmac sha256 방식으로 네이버 클라우드 API SecretKey를 이용하여 $message 문자열을 암호화 즉, 해시값을 만들고, 다시 base64로 인코딩합니다.

http 호출 헤더값 설정

# Return request headers
return @{
    "x-ncp-apigw-timestamp" = $unixtimestamp;
    "x-ncp-iam-access-key" = $ncloud_accesskey;
    "x-ncp-apigw-signature-v2" = $signature
}

API를 호출할 때는 http 헤더값에 다음 3가지를 추가해서 호출합니다.

  • 유닉스 타임스탬프
  • 네이버 클라우드 API AccessKey
  • hmac_256 으로 암호화한 문자열

여기서 전송하는 타임스탬프는 위에서 $message를 암호화할 때 사용한 타임스탬프와 동일한 값이어야 합니다.


네이버 클라우드 인증키

$ncloud_accesskey = "Ncloud AccessKey"
$ncloud_secretkey = "Ncloud SecretKey"	

네이버 클라우드 인증키는 네이버 클라우드 포탈 -> 마이페이지 -> 계정관리 -> 인증키 관리 - API 인증키 관리 메뉴에서 Access Key ID와 Secret Key를 가져오셔야 하며, 아직 만들어진 Key가 없다면 새로 만드셔야 합니다.

Ncloud API 인증키 생성하는 방법

api 호출

$headers = Sign-Request $api_server $api_url $apicall_method $ncloud_accesskey $ncloud_secretkey
Invoke-WebRequest -Uri $api_full_url -Method $apicall_method -Headers $headers  -Body $body 

이제 위에서 준비한 값들을 사용해서 API를 호출합니다.
리턴값은 호출하는 용도별로 json 또는 xml 형태로 반환됩니다.

응답 예시

<?xml version="1.0" encoding="UTF-8"?>
<getProductPriceListResponse>
  <requestId>397d3d13-2b2a-42d2-96d0-20ff63df69dc</requestId>
  <returnCode>0</returnCode>
  <returnMessage>success</returnMessage>
  <totalRows>121</totalRows>
  <productPriceList>
    <productPrice>
      <productItemKind>
        <code>VSVR</code>
        <codeName>Server (VPC)</codeName>
      </productItemKind>
      <productItemKindDetail>
        <code>BM</code>
        <codeName>BareMetal</codeName>
      </productItemKindDetail>
     ''' 중략 '''
      <softwareType/>
      <productType>
        <code>BM</code>
        <codeName>BareMetal</codeName>
      </productType>
      <productType>
        <code>BM</code>
        <codeName>BareMetal</codeName>
      </productType>
      <productTypeDetail/>
      <gpuCount>0</gpuCount>
      <cpuCount>24</cpuCount>
      <memorySize>137438953472</memorySize>
      <baseBlockStorageSize>4123168604160</baseBlockStorageSize>
      <dbKind/>
      <osInfomation/>
      <platformType/>
      <osType/>
      <platformCategoryCode/>
      <diskType>
        <code>LOCAL</code>
        <codeName>Local storage</codeName>
      </diskType>
      <diskDetailType>
        <code>SSD</code>
        <codeName>SSD</codeName>
      </diskDetailType>
      <generationCode>G1</generationCode>     
    ''' 중략 '''
  </productPriceList>
</getProductPriceListResponse>

참고 URL

  1. 네이버 클라우드 API 가이드
Tags: api windows