Newer
Older
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
param (
[alias('mount')][parameter(Mandatory=$true)]$aws_mount,
[alias('role')]$iam_role = "limited-admin",
[switch]$force
)
if (!(which vault)) {write-warning "vault cli not found. Exiting."; exit 1}
# ensure logged into vault
$token_response = $(vault token lookup -format=json 2>&1)
if ($token_response.Exception) {write-warning "Missing client token. Login to Vault."; exit 1}
# check for stashed creds
$stash = $(vault read -format=json cubbyhole/aws_creds 2>&1)
# use stashed creds if consistent with environment
if (!($stash -match '^No value') -and ($stash -ne $NULL) -and ($force -eq $false)) {
$stash_obj = $stash | ConvertFrom-Json
$expiration = [datetime]$stash_obj.data.expiration
if ((get-date) -lt $expiration) {
if (($env:AWS_ACCESS_KEY_ID -eq $stash_obj.data.access_key_id) -and ($env:AWS_SECRET_ACCESS_KEY -eq $stash_obj.data.secret_access_key)) {
write-host "using cached credentials expiring on $expiration"
exit 0;
} else {
write-warning "Cached credentials do not match current environment."
write-host -ForegroundColor Cyan "Use cached credentials (Y) or get new (ENTER) "
$use_creds = read-host -prompt "?"
if ($use_creds -imatch "^Y$") {
$env:AWS_ACCESS_KEY_ID = $stash_obj.data.access_key_id
$env:AWS_SECRET_ACCESS_KEY = $stash_obj.data.secret_access_key
write-host "using cached credentials expiring on $expiration"
exit 0;
} else {
write-host "getting new aws credentials..."
}
}
} else {
write-host "Credentials expired on $expiration"
}
}
$now = get-date
# generate creds
$aws_cred = $(vault read -format=json $aws_mount/creds/$iam_role)
if (($aws_cred -match '^No value') -or ($aws_cred -eq $NULL)) {
if (!($aws_cred)) {write-warning "Unable to retrieve credentials from $aws_mount/creds/$iam_role"; exit 1}
}
$aws_cred_obj = $aws_cred | ConvertFrom-Json
$aws_cred_expiration = $now.AddSeconds($aws_cred_obj.lease_duration)
$aws_cred_access_key = $aws_cred_obj.data.access_key
$aws_cred_secret_key = $aws_cred_obj.data.secret_key
$aws_cred_lease_id = $aws_cred_obj.lease_id
if ($aws_cred_access_key -and $aws_cred_secret_key) {
$env:AWS_SECRET_ACCESS_KEY=$aws_cred_secret_key
$env:AWS_ACCESS_KEY_ID=$aws_cred_access_key
write-host -ForegroundColor Cyan "generated AWS credentials:"
write-host "lease_id: $($aws_cred_obj.lease_id)"
write-host "lease_expiration: $($aws_cred_expiration)"
} else {
write-warning "Unable to generate AWS credentials."
exit 1;
}
# stash creds
$stash_response = $(vault write cubbyhole/aws_creds access_key_id=$aws_cred_access_key secret_access_key=$aws_cred_secret_key expiration=$aws_cred_expiration lease_id=$aws_cred_lease_id 2>&1)
if ($stash_response -notmatch '^Success') {
write-warning "Unable to stash generated AWS credentials in vault"
} else {
write-host "Stashed credentials in vault"
}