-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.tf
89 lines (82 loc) · 2.7 KB
/
main.tf
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
provider "spotinst" {
token = var.spotinst_token
}
# Create AWS account on Spot
resource "spotinst_account_aws" "spot_acct" {
name=var.name
}
# Create externalId
resource "null_resource" "externalid" {
provisioner "local-exec" {
command = <<EOT
curl -X POST https://api.spotinst.io/setup/credentials/aws/externalId?accountId=${spotinst_account_aws.spot_acct.id} \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${var.spotinst_token}" > externalid.json
EOT
}
}
data "local_file" "externalid" {
depends_on = [null_resource.externalid]
filename = "externalid.json"
}
locals {
user_data = jsondecode(data.local_file.externalid.content)
externalids = [for item in local.user_data.response.items : item.externalId]
}
# Create AWS Role for Spot
resource "aws_iam_role" "spot"{
name = var.role_name == null ? "SpotRole-${spotinst_account_aws.spot_acct.id}-${random_id.random_string.hex}" : var.role_name
provisioner "local-exec" {
# Without this set-cloud-credentials fails
command = "sleep 10"
}
assume_role_policy = <<-EOT
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::922761411349:root"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"sts:ExternalId": "${local.externalids[0]}"
}
}
}
]
}
EOT
tags = var.tags
lifecycle {
ignore_changes = [tags]
}
}
# Create IAM Policy
resource "aws_iam_policy" "spot" {
name = var.policy_name == null ? "Spot-Policy-${spotinst_account_aws.spot_acct.id}-${random_id.random_string.hex}" : var.policy_name
path = "/"
description = "Spot by NetApp IAM policy to manage resources"
policy = var.policy_file == null ? templatefile("${path.module}/spot_policy.json", {}) : var.policy_file
tags = var.tags
lifecycle {
ignore_changes = [tags]
}
}
# Attach the policy to the role
resource "aws_iam_role_policy_attachment" "spot" {
role = aws_iam_role.spot.name
policy_arn = aws_iam_policy.spot.arn
}
resource "time_sleep" "wait_05_seconds" {
depends_on = [aws_iam_role_policy_attachment.spot]
create_duration = "5s"
}
# Link the Role ARN to the Spot Account
resource "spotinst_credentials_aws" "credential" {
depends_on = [aws_iam_role_policy_attachment.spot, time_sleep.wait_05_seconds]
iamrole = aws_iam_role.spot.arn
account_id = spotinst_account_aws.spot_acct.id
}