TheKoguryo's 기술 블로그

Version 2019.06.03

14.3.2 Bash 샘플 클라이언트

Bash 샘플 클라이언트

Step 1. 샘플코드 준비

Bash 샘플코드의 원본은 아래 링크에서 확인할 수 있습니다. 아래 샘플 코드에서 보듯이 oci-curl 함수를 정의하여, Request Signature에 필요한 모든 작업은 oci-curl에서 수행되게 만들어 놓았습니다. 사용자는 호출 정보만 파라미터로 전달하여, 사용하면 됩니다.

https://docs.cloud.oracle.com/iaas/Content/API/Concepts/signingrequests.htm#Bash

# Version: 1.0.2
# Usage:
# oci-curl <host> <method> [file-to-send-as-body] <request-target> [extra-curl-args]
# ex:
# oci-curl iaas.us-ashburn-1.oraclecloud.com get "/20160918/instances?compartmentId=some-compartment-ocid"
# oci-curl iaas.us-ashburn-1.oraclecloud.com post ./request.json "/20160918/vcns"

function oci-curl {
	# TODO: update these values to your own
		local tenancyId="ocid1.tenancy.oc1..aaaaaaaaba3pv6wkcr4jqae5f15p2b2m2yt2j6rx32uzr4h25vqstifsfdsq";
		local authUserId="ocid1.user.oc1..aaaaaaaat5nvwcna5j6aqzjcaty5eqbb6qt2jvpkanghtgdaqedqw3rynjq";
		local keyFingerprint="20:3b:97:13:55:1c:5b:0d:d3:37:d8:50:4e:c5:3a:34";
		local privateKeyPath="/Users/someuser/.oci/oci_api_key.pem";

	local alg=rsa-sha256
	local sigVersion="1"
	local now="$(LC_ALL=C \date -u "+%a, %d %h %Y %H:%M:%S GMT")"
	local host=$1
	local method=$2
	local extra_args
	local keyId="$tenancyId/$authUserId/$keyFingerprint"
	
	case $method in
				
		"get" | "GET")
		local target=$3
		extra_args=("${@: 4}")
		local curl_method="GET";
		local request_method="get";
		;;				
				
		"delete" | "DELETE")
		local target=$3
		extra_args=("${@: 4}")
		local curl_method="DELETE";
		local request_method="delete";
		;;		
				
		"head" | "HEAD")
		local target=$3
		extra_args=("--head" "${@: 4}")
		local curl_method="HEAD";
		local request_method="head";
		;;
				
		"post" | "POST")
		local body=$3
		local target=$4
		extra_args=("${@: 5}")
		local curl_method="POST";
		local request_method="post";
		local content_sha256="$(openssl dgst -binary -sha256 < $body | openssl enc -e -base64)";
		local content_type="application/json";
		local content_length="$(wc -c < $body | xargs)";
		;;		
		
		"put" | "PUT")
		local body=$3
		local target=$4
		extra_args=("${@: 5}")
		local curl_method="PUT"
		local request_method="put"
		local content_sha256="$(openssl dgst -binary -sha256 < $body | openssl enc -e -base64)";
		local content_type="application/json";
		local content_length="$(wc -c < $body | xargs)";
		;;				
		
		*) echo "invalid method"; return;;
esac

# This line will url encode all special characters in the request target except "/", "?", "=", and "&", since those characters are used 
# in the request target to indicate path and query string structure. If you need to encode any of "/", "?", "=", or "&", such as when
# used as part of a path value or query string key or value, you will need to do that yourself in the request target you pass in.

local escaped_target="$(echo $( rawurlencode "$target" ))"	
local request_target="(request-target): $request_method $escaped_target"
local date_header="date: $now"
local host_header="host: $host"
local content_sha256_header="x-content-sha256: $content_sha256"
local content_type_header="content-type: $content_type"
local content_length_header="content-length: $content_length"
local signing_string="$request_target\n$date_header\n$host_header"
local headers="(request-target) date host"
local curl_header_args
curl_header_args=(-H "$date_header")
local body_arg
body_arg=()
				
if [ "$curl_method" = "PUT" -o "$curl_method" = "POST" ]; then
	signing_string="$signing_string\n$content_sha256_header\n$content_type_header\n$content_length_header"
	headers=$headers" x-content-sha256 content-type content-length"
	curl_header_args=("${curl_header_args[@]}" -H "$content_sha256_header" -H "$content_type_header" -H "$content_length_header")
	body_arg=(--data-binary @${body})
fi
				
local sig=$(printf '%b' "$signing_string" | \
			openssl dgst -sha256 -sign $privateKeyPath | \
			openssl enc -e -base64 | tr -d '\n')

curl "${extra_args[@]}" "${body_arg[@]}" -X $curl_method -sS https://${host}${escaped_target} "${curl_header_args[@]}" \
	-H "Authorization: Signature version=\"$sigVersion\",keyId=\"$keyId\",algorithm=\"$alg\",headers=\"${headers}\",signature=\"$sig\""
}				
# url encode all special characters except "/", "?", "=", and "&"
function rawurlencode {
  local string="${1}"
  local strlen=${#string}
  local encoded=""
  local pos c o	

  for (( pos=0 ; pos<strlen ; pos++ )); do
	c=${string:$pos:1}
	case "$c" in
		[-_.~a-zA-Z0-9] | "/" | "?" | "=" | "&" ) o="${c}" ;;
		* )               printf -v o '%%%02x' "'$c"
	esac
	encoded+="${o}"
	done

	echo "${encoded}"
}

Step 2. 연결정보 설정

  1. 위 샘플 코드를 복사하여 oci-curl.sh 이름으로 저장합니다.

  2. oci-curl.sh 내용중에 연결정보를 사용자에 맞게 업데이트합니다.

      local tenancyId="ocid1.tenancy.oc1..aaaaaaaaba3pv6wkcr4jqae5f15p2b2m2yt2j6rx32uzr4h25vqstifsfdsq";
      local authUserId="ocid1.user.oc1..aaaaaaaat5nvwcna5j6aqzjcaty5eqbb6qt2jvpkanghtgdaqedqw3rynjq";
      local keyFingerprint="20:3b:97:13:55:1c:5b:0d:d3:37:d8:50:4e:c5:3a:34";
      local privateKeyPath="/Users/someuser/.oci/oci_api_key.pem";
  3. 아래 명령을 수행하면 oci-curl 함수를 현재 세션에서 실행할 수 있게 됩니다.

    oracle@ubuntu:~/oci-curl$ . ./oci-curl.sh
    oracle@ubuntu:~/oci-curl$ oci-curl
    invalid method
    oracle@ubuntu:~/oci-curl$

Step 3. 사용자 조회 REST API 실행

  1. ListUsers 설명

  2. 사용방법

    oci-curl <host> <method> [file-to-send-as-body] <request-target> [extra-curl-args]
  3. 사용예시 - tenancy내 모든 사용자 조회
    아래와 같이 사용자가 조회되는 것을 확인할 수 있습니다.

    • extra-curl-args로 -i를 입력하면 응답메시지 헤더를 확인할 수 있습니다.
oracle@ubuntu:~/oci-curl$ oci-curl identity.us-ashburn-1.oraclecloud.com GET "/20160918/users/?compartmentId=ocid1.tenancy.oc1..aaaaaaaa4xqu77ge5lsioskp53247ohk7rs3bfyodsb2bf6h6mhahlzXXXXX" -i
HTTP/1.1 200 OK
Date: Sun, 19 May 2019 08:15:10 GMT
Content-Type: application/json
Content-Length: 3152
Connection: keep-alive
opc-request-id: /2BF47D321833EFD084DBAAC718095658/E21191A3BE4584980FA4A533A6E50927
opc-next-page: AAAAAAAAAAJleUpyYVdRaU9pSTBPRGNpTENKbGJtTWlPaUpCTWpVMlIwTk5JaXdpWVd4bklqb2laR2x5SW4wLi53d0wzM0RiMnVMNGJld0FjLmVyQjNfU3RfbVpmNTRkQS1GRVlLaFk4N196S3dzakVRUVhicnZZeUowSVJxYWdpQnZSVWtEQW9ZWlRNX0hKQ1RzcEVFYTU1Qkt0cEFBdlJXdlRrdWlvNlBRRWpoUG5FNDhCSXpjZUd5UTlOOFBOdkVNRzFoLTEzRUJHbzJzSFJ0Q0hpTU8weFRMRHI4UjlhVHI4SnFjZVJyMXVkT3hlZWRVMmJ2Y1pZenlUM05aTXAzeG5HMDc4ZGpKTHBmbWViWFhtSHBLb1JrQ0JXZHl0VTlkNzRIYksyU19STlk5WWlKSGRRczhjenVzOEE2MGNJS2JDY1MyZ0FGVFhsTmI3UnNXS05ZaHlhTXZUcVZVX05JUTJETkstbVB1TUdjRFYwQU5GTkg1NzdISDRFbDY3R0w4TlAwOVBfeFprSFZrOWNFU0xfMXRHWDRUcUF5d0NoMVVrak5Nc2drb21VbkMzMWNQVThTdjBFQ1ZsS2ZjVGlmTGxCVkxqS0o1a1o1R3RoWUJVLXhJcGxHenJXNjZRUWFsbTlVM2VPVFMxbDFKZi1HS0F3ZGlDY0E1aU1ldWtxNE92d3JmT3Z6aXFGdktJUFZoeldpeHNQaF81ZVE5UzgxWlJmSURHU1dpNU85cUdXZ2I3WnA0bVhnOWtIaGFqY2YyMjJLdlNSTS0xSVFLcnlJazVDUzhranVZR2hJNE9Oa2JrUXIuWloyejcyZ05EUGVCODNZdFVJZEptZw==
Cache-Control: no-cache, no-store, must-revalidate
opc-limit: 25
Pragma: no-cache
X-Content-Type-Options: nosniff

[ {
  "capabilities" : {
    "canUseConsolePassword" : true,
    "canUseApiKeys" : true,
    "canUseAuthTokens" : true,
    "canUseSmtpCredentials" : true,
    "canUseCustomerSecretKeys" : true
  },
  "emailVerified" : false,
  "identityProviderId" : null,
  "externalIdentifier" : null,
  "timeModified" : "2019-05-13T04:56:33.114Z",
  "isMfaActivated" : false,
  "id" : "ocid1.user.oc1..aaaaaaaa2um5iz27ms3cf43tp77k6tjjn4kbzjrilajem4xaiyl5vqeXXXXXX",
  "compartmentId" : "ocid1.tenancy.oc1..aaaaaaaa4xqu77ge5lsioskp53247ohk7rs3bfyodsb2bf6h6mhahlzXXXXX",
  "name" : "oci.admin",
  "description" : "OCI Admin",
  "timeCreated" : "2019-05-13T04:55:06.156Z",
  "freeformTags" : { },
  "definedTags" : { },
  "lifecycleState" : "ACTIVE"
}, {
  "capabilities" : {
    "canUseConsolePassword" : true,
    "canUseApiKeys" : true,
    "canUseAuthTokens" : true,
    "canUseSmtpCredentials" : true,
    "canUseCustomerSecretKeys" : true
  },
  "emailVerified" : false,
  "identityProviderId" : null,
  "externalIdentifier" : null,
  "timeModified" : "2019-05-13T04:11:10.299Z",
  "isMfaActivated" : false,
  "id" : "ocid1.user.oc1..aaaaaaaaeqzpkd5u7humc3xinp3ika4sjhnhqj5jbvfcvdqg4tdx4jqXXXXX",
  "compartmentId" : "ocid1.tenancy.oc1..aaaaaaaa4xqu77ge5lsioskp53247ohk7rs3bfyodsb2bf6h6mhahlzXXXXX",
  "name" : "sandboxer",
  "description" : "sandboxer",
  "timeCreated" : "2019-05-13T04:09:32.205Z",
  "freeformTags" : { },
  "definedTags" : { },
  "lifecycleState" : "ACTIVE"
} ]oracle@ubuntu:~/oci-curl$

Step 4. 사용자 생성 REST API 실행

  1. CreateUser 설명

    {
      "compartmentId" : "tenancy OCID",
      "name" : "사용자 이름",
      "description" : "설명"
    }
  2. 사용방법

    oci-curl <host> <method> [file-to-send-as-body] <request-target> [extra-curl-args]
  3. 사용예시 - 사용자 생성
    아래와 같이 사용자가 만들어 지는 것을 확인할 수 있습니다.

    oracle@ubuntu:~/oci-curl$ cat create_user_request.json
    {
    "compartmentId" : "ocid1.tenancy.oc1..aaaaaaaa4xqu77ge5lsioskp53247ohk7rs3bfyodsb2bf6h6mhahlzXXXXX",
    "description" : "KilDong OCI",
    "name" : "kildong.oci@example.com"
    }
    oracle@ubuntu:~/oci-curl$ oci-curl identity.us-ashburn-1.oraclecloud.com POST ./create_user_request.json "/20160918/users/" -i
    HTTP/1.1 200 OK
    Date: Sun, 19 May 2019 08:33:39 GMT
    Content-Type: application/json
    Content-Length: 748
    Connection: keep-alive
    opc-request-id: /3010DE4E4BFBF1963248FEC32FC1FFBA/FB514FBFDEAA1C6845BCAA66C2B4C31D
    Cache-Control: no-cache, no-store, must-revalidate
    ETag: 42e800af061123f725163d2b538d1f9560022422
    Pragma: no-cache
    Location: http://identity.us-ashburn-1.oraclecloud.com/20160918/users/ocid1.user.oc1..aaaaaaaaniw34appawah7sicksca37hhzhq7pvfkmhwskf4gbkt3ctxXXXXXX
    X-Content-Type-Options: nosniff
    {
    "capabilities" : {
    "canUseConsolePassword" : true,
    "canUseApiKeys" : true,
    "canUseAuthTokens" : true,
    "canUseSmtpCredentials" : true,
    "canUseCustomerSecretKeys" : true
    },
    "emailVerified" : false,
    "identityProviderId" : null,
    "externalIdentifier" : null,
    "timeModified" : "2019-05-19T08:33:39.788Z",
    "isMfaActivated" : false,
    "id" : "ocid1.user.oc1..aaaaaaaaniw34appawah7sicksca37hhzhq7pvfkmhwskf4gbkt3ctxXXXXX",
    "compartmentId" : "ocid1.tenancy.oc1..aaaaaaaa4xqu77ge5lsioskp53247ohk7rs3bfyodsb2bf6h6mhahlzXXXXX",
    "name" : "kildong.oci@example.com",
    "description" : "KilDong OCI",
    "timeCreated" : "2019-05-19T08:33:39.788Z",
    "freeformTags" : { },
    "definedTags" : { },
    "lifecycleState" : "ACTIVE"
    }oracle@ubuntu:~/oci-curl$
  4. 생성결과 확인 그림



** 이 글은 개인으로서, 개인의 시간을 할애하여 작성된 글입니다. 글의 내용에 오류가 있을 수 있으며, 글 속의 의견은 개인적인 의견입니다. **
Last updated on 19 May 2019