terraform-provider-google/google/data_source_google_service_account_key.go
Jonathan Pentecost f8a3335bf9 service_account_key: regression fix for v1.14 (#1664)
Commit 8f31fec introduced a bug for the 'service_account_key' resource
where it required a project be set either in the provider or in the
resource for 'service_account_key', but a project isn't required if the
service account is a service account fully qualified name or a service
account email.

This PR relaxes the requirement that a project needs to be set for the
'service_account_key' resource, 'service_account' datasource and
'service_account_key' datasource, but will error if we try to build a
fully qualified name from a service account id when no project can be
found.

This also cleans up 'serviceAccountFQN' so it is slightly easier to
follow and return an error if there is no project but we need one to
build the service account fully qualified name.

Fixes: #1655
2018-06-18 13:37:41 -07:00

70 lines
1.7 KiB
Go

package google
import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)
func dataSourceGoogleServiceAccountKey() *schema.Resource {
return &schema.Resource{
Read: dataSourceGoogleServiceAccountKeyRead,
Schema: map[string]*schema.Schema{
"service_account_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"public_key_type": &schema.Schema{
Type: schema.TypeString,
Default: "TYPE_X509_PEM_FILE",
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"TYPE_NONE", "TYPE_X509_PEM_FILE", "TYPE_RAW_PUBLIC_KEY"}, false),
},
"project": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
// Computed
"name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"key_algorithm": {
Type: schema.TypeString,
Computed: true,
},
"public_key": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceGoogleServiceAccountKeyRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
serviceAccountName, err := serviceAccountFQN(d.Get("service_account_id").(string), d, config)
if err != nil {
return err
}
publicKeyType := d.Get("public_key_type").(string)
// Confirm the service account key exists
sak, err := config.clientIAM.Projects.ServiceAccounts.Keys.Get(serviceAccountName).PublicKeyType(publicKeyType).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Service Account Key %q", serviceAccountName))
}
d.SetId(sak.Name)
d.Set("name", sak.Name)
d.Set("key_algorithm", sak.KeyAlgorithm)
d.Set("public_key", sak.PublicKeyData)
return nil
}