How to interact with the Chef Server using the Chef Server API using Shell script

本文介绍了一个使用Shell脚本实现的功能,用于搜索并返回Chef配置目录路径。脚本通过递归方式向上查找目录,直到找到或默认选择~/.chef作为配置位置。

!/usr/bin/env bash

 

_chef_dir () {

# Helper function:

# Recursive function that searches for chef configuration directory

# It looks upward from the cwd until it hits /. If no directory is found,

# ~/.chef is chosen if it exists

# You could simply hard-code the path below

 

if [ "$PWD" = "/" ]; then

if [ -d ".chef" ]; then

echo "/.chef"

elif [ -d "$HOME/.chef" ]; then

echo "$HOME/.chef"

fi

return

fi

 

if [ -d '.chef' ];then

echo "${PWD}/.chef"

else

(cd ..; _chef_dir)

fi

}

 

_chomp () {

# helper function to remove newlines

awk '{printf "%s", $0}'

}

 

chef_api_request() {

# This is the meat-and-potatoes, or rice-and-vegetables, your preference really.

 

local method path body timestamp chef_server_url client_name hashed_body hashed_path

local canonical_request headers auth_headers

 

chef_server_url="https://api.opscode.com/organizations/my_org"

# '/organizations/ORG_NAME' is needed for Hosted Chef or Private Chef

if echo $chef_server_url | grep -q "/organizations/" ; then

endpoint=/organizations/${chef_server_url#*/organizations/}${2%%\?*}

else

endpoint=${$2%%\?*}

fi

path=${chef_server_url}$2

client_name="chef_user"

method=$1

body=$3

 

hashed_path=$(echo -n "$endpoint" | openssl dgst -sha1 -binary | openssl enc -base64)

hashed_body=$(echo -n "$body" | openssl dgst -sha1 -binary | openssl enc -base64)

timestamp=$(date -u "+%Y-%m-%dT%H:%M:%SZ")

 

canonical_request="Method:$method\nHashed Path:$hashed_path\nX-Ops-Content-Hash:$hashed_body\nX-Ops-Timestamp:$timestamp\nX-Ops-UserId:$client_name"

headers="-H X-Ops-Timestamp:$timestamp \

-H X-Ops-Userid:$client_name \

-H X-Chef-Version:0.10.4 \

-H Accept:application/json \

-H X-Ops-Content-Hash:$hashed_body \

-H X-Ops-Sign:version=1.0"

 

auth_headers=$(printf "$canonical_request" | openssl rsautl -sign -inkey \

"$(_chef_dir)/${client_name}.pem" | openssl enc -base64 | _chomp | awk '{ll=int(length/60);i=0; \

while (i<=ll) {printf " -H X-Ops-Authorization-%s:%s", i+1, substr($0,i*60+1,60);i=i+1}}')

 

case $method in

GET)

curl_command="curl $headers $auth_headers $path"

$curl_command

;;

*)

echo "Unknown Method. I only know: GET" >&2

return 1

;;

esac

}

 

chef_api_request "$@"

转载于:https://www.cnblogs.com/suizhihao/p/3156641.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值