forked from rut31337/order_svc
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcommon.sh
108 lines (85 loc) · 2.49 KB
/
common.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/bash
# get a token from CloudForms, keep the current if it's still valid.
get_token() {
# init variables to support '-u' mode
tok=${tok:-''}
tok_expire_on=${tok_expire_on:-0}
if [ -n "$tok" ]; then
# verify it's still valid
if [ "$tok_expire_on" -gt "$(date +%s)" ]; then
return
fi
fi
: "${username?"Username not set"}"
: "${password?"password not set"}"
: "${uri?"uri not set"}"
CURLOPT=${CURLOPT:-}
token_info=$(curl "${CURLOPT}" -s --user "${username}:${password}" \
-X GET -H "Accept: application/json" \
"${uri}/api/auth" \
| jq -r '.auth_token + ";" + (.token_ttl|tostring)')
tok=${token_info%;*}
tok_ttl=${token_info#*;}
if [ -z "${tok}" ] || [ -z "${tok_ttl}" ]; then
echo >&2 "issue with token"
exit 1
fi
export tok
tok_expire_on=$(date --date="now + ${tok_ttl} seconds" +%s)
export tok_expire_on
}
# curl shortcut to GET, you have to provide complete URI
cfget() {
get_token
CURLOPT=${CURLOPT:-}
DEBUG=${DEBUG:-}
local output
output=$(mktemp)
curl "${CURLOPT}" -s \
-H "X-Auth-Token: ${tok}" \
-H "Content-Type: application/json" \
-X GET \
"$@" | tee -a "${output}"
if [ -n "$DEBUG" ] && [ "$DEBUG" != "false" ]; then
echo >&2 ""
echo >&2 "DEBUG curl output"
echo >&2 ""
if ! jq . < "${output}" >&2; then
cat "${output}" >&2
fi
echo >&2 ""
fi
rm "${output}"
}
# curl shortcut to POST, you have to provide complete URI
cfpost() {
get_token
CURLOPT=${CURLOPT:-}
DEBUG=${DEBUG:-}
local output
output=$(mktemp)
curl "${CURLOPT}" -s \
-H "X-Auth-Token: ${tok}" \
-H "Content-Type: application/json" \
-X POST \
"$@" | tee -a "${output}"
if [ -n "$DEBUG" ] && [ "$DEBUG" != "false" ]; then
echo >&2 ""
echo >&2 "DEBUG curl output"
echo >&2 ""
if ! jq . < "${output}" >&2; then
cat "${output}" >&2
fi
echo >&2 ""
fi
rm "${output}"
}
# Run this as admin
get_my_user_id() {
cfget \
"${uri}/api/users?attributes=id,userid,name&filter[]=userid='${username}'&expand=resources" \
| jq -r ".resources[] | select(.userid == \"${username}\") | .id"
}
json_escape () {
printf '%s' "$1" | python -c 'import json,sys; print(json.dumps(sys.stdin.read()))'
}