|
7 | 7 | "fmt" |
8 | 8 | "io" |
9 | 9 | "log" |
| 10 | + "net/http" |
10 | 11 | "os" |
11 | 12 | "strconv" |
12 | 13 | "time" |
@@ -83,6 +84,12 @@ func ResourceMachineCreate(ctx context.Context, d *terraform_schema.ResourceData |
83 | 84 | } |
84 | 85 | } |
85 | 86 |
|
| 87 | + // Lookup service account if set. |
| 88 | + svcAccount, svcTokenAutomount, err := getServiceAccount(ctx, conn, namespace, d.Get("instance_permission_set").(string)) |
| 89 | + if err != nil { |
| 90 | + return err |
| 91 | + } |
| 92 | + |
86 | 93 | // Leave the job running for 30 seconds after the termination signal, but remove it immediately after terminating. |
87 | 94 | jobTTLSecondsAfterFinished := int32(0) |
88 | 95 | jobTerminationGracePeriod := int64(30) |
@@ -126,6 +133,8 @@ func ResourceMachineCreate(ctx context.Context, d *terraform_schema.ResourceData |
126 | 133 | }, |
127 | 134 | }, |
128 | 135 | }, |
| 136 | + ServiceAccountName: svcAccount, |
| 137 | + AutomountServiceAccountToken: svcTokenAutomount, |
129 | 138 | }, |
130 | 139 | }, |
131 | 140 | }, |
@@ -434,3 +443,17 @@ func ResourceMachineLogs(ctx context.Context, d *terraform_schema.ResourceData, |
434 | 443 |
|
435 | 444 | return buf.String(), nil |
436 | 445 | } |
| 446 | + |
| 447 | +func getServiceAccount(ctx context.Context, client kubernetes.Interface, namespace string, accountName string) (account string, automountToken *bool, err error) { |
| 448 | + if accountName == "" { |
| 449 | + return "", nil, nil |
| 450 | + } |
| 451 | + acct, err := client.CoreV1().ServiceAccounts(namespace).Get(ctx, accountName, kubernetes_meta.GetOptions{}) |
| 452 | + if err != nil { |
| 453 | + if statusErr, ok := err.(*kubernetes_errors.StatusError); ok && statusErr.ErrStatus.Code == http.StatusNotFound { |
| 454 | + return "", nil, fmt.Errorf("service account %q does not exist in namespace %q", accountName, namespace) |
| 455 | + } |
| 456 | + return "", nil, fmt.Errorf("failed to lookup service account %q in namespace %q: %w", accountName, namespace, err) |
| 457 | + } |
| 458 | + return accountName, acct.AutomountServiceAccountToken, nil |
| 459 | +} |
0 commit comments