|
| 1 | +package google |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/hashicorp/terraform/helper/schema" |
| 11 | + iamcredentials "google.golang.org/api/iamcredentials/v1" |
| 12 | +) |
| 13 | + |
| 14 | +func dataSourceGoogleServiceAccountAccessToken() *schema.Resource { |
| 15 | + |
| 16 | + return &schema.Resource{ |
| 17 | + Read: dataSourceGoogleServiceAccountAccessTokenRead, |
| 18 | + Schema: map[string]*schema.Schema{ |
| 19 | + "target_service_account": { |
| 20 | + Type: schema.TypeString, |
| 21 | + Required: true, |
| 22 | + ValidateFunc: validateRegexp("(" + strings.Join(PossibleServiceAccountNames, "|") + ")"), |
| 23 | + }, |
| 24 | + "access_token": { |
| 25 | + Type: schema.TypeString, |
| 26 | + Sensitive: true, |
| 27 | + Computed: true, |
| 28 | + }, |
| 29 | + "scopes": { |
| 30 | + Type: schema.TypeSet, |
| 31 | + Required: true, |
| 32 | + Elem: &schema.Schema{ |
| 33 | + Type: schema.TypeString, |
| 34 | + StateFunc: func(v interface{}) string { |
| 35 | + return canonicalizeServiceScope(v.(string)) |
| 36 | + }, |
| 37 | + }, |
| 38 | + // ValidateFunc is not yet supported on lists or sets. |
| 39 | + }, |
| 40 | + "delegates": { |
| 41 | + Type: schema.TypeSet, |
| 42 | + Optional: true, |
| 43 | + Elem: &schema.Schema{ |
| 44 | + Type: schema.TypeString, |
| 45 | + ValidateFunc: validateRegexp(ServiceAccountLinkRegex), |
| 46 | + }, |
| 47 | + }, |
| 48 | + "lifetime": { |
| 49 | + Type: schema.TypeString, |
| 50 | + Optional: true, |
| 51 | + ValidateFunc: validateDuration(), // duration <=3600s; TODO: support validteDuration(min,max) |
| 52 | + Default: "3600s", |
| 53 | + }, |
| 54 | + }, |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +func dataSourceGoogleServiceAccountAccessTokenRead(d *schema.ResourceData, meta interface{}) error { |
| 59 | + config := meta.(*Config) |
| 60 | + log.Printf("[INFO] Acquire Service Account AccessToken for %s", d.Get("target_service_account").(string)) |
| 61 | + |
| 62 | + service := config.clientIamCredentials |
| 63 | + |
| 64 | + name := fmt.Sprintf("projects/-/serviceAccounts/%s", d.Get("target_service_account").(string)) |
| 65 | + tokenRequest := &iamcredentials.GenerateAccessTokenRequest{ |
| 66 | + Lifetime: d.Get("lifetime").(string), |
| 67 | + Delegates: convertStringSet(d.Get("delegates").(*schema.Set)), |
| 68 | + Scope: canonicalizeServiceScopes(convertStringSet(d.Get("scopes").(*schema.Set))), |
| 69 | + } |
| 70 | + at, err := service.Projects.ServiceAccounts.GenerateAccessToken(name, tokenRequest).Do() |
| 71 | + if err != nil { |
| 72 | + return err |
| 73 | + } |
| 74 | + |
| 75 | + d.SetId(time.Now().UTC().String()) |
| 76 | + d.Set("access_token", at.AccessToken) |
| 77 | + |
| 78 | + return nil |
| 79 | +} |
0 commit comments