Assign IAM policies
This page describes how to programmatically grant access to an Identity and Access Management API resource.
Roles
The list of roles that can be assigned to Identity and Access Management API resources can be found in the reference page for IAM roles.
IAM Members
The IAM members that can be assigned to an IAM policy binding can be one of the following:
Member | Description |
---|---|
user:12345567890 | Used to grant roles only to a specific user. |
serviceAccount:12345567890 | Used to grant roles only to a specific service account. |
warning
The role allUsers
cannot be assigned to Identity and Access Management resource policies for security reasons.
Sample
The following code sample shows how to assign a service account IAM policy with the role roles/iam.serviceAccountAdmin
. This means that that the policy member will be allowed full control over the specified service account, including resource deletion and IAM policy updates.
Replace [SERVICE-ACCOUNT]
with the resource name of the service account that the policy should be assigned to, e.g. users/123/serviceAccounts/my-service-account
.
Replace [MEMBER]
with the resource name of the member to be assigned to the policy binding, e.g. user:12345567890
.
tip
Tip: do not forget to replace CLIENT-ID
and CLIENT-SECRET
with valid IAM Service Account client credentials.
caution
The SetIamPolicy
method will always replace (overwrite) any previously defined policy.
- Golang
package main
import (
"context"
"log"
"golang.org/x/oauth2/clientcredentials"
"google.golang.org/api/option"
"google.golang.org/genproto/googleapis/iam/v1"
gapic "github.com/animeapis/api-go-client/iam/admin/v1alpha1"
)
var (
ServiceAccount = "[SERVICE-ACCOUNT]"
Member = "[MEMBER]"
Role = "roles/iam.serviceAccountAdmin"
ClientID = "[CLIENT-ID]"
ClientSecret = "[CLIENT-SECRET]"
)
var (
TokenURL = "https://accounts.animeshon.com/o/oauth2/token"
Endpoint = "iam.animeapis.com:443"
)
func main() {
ctx := context.Background()
config := &clientcredentials.Config{
ClientID: ClientID,
ClientSecret: ClientSecret,
TokenURL: TokenURL,
}
options := []option.ClientOption{
option.WithEndpoint(Endpoint),
option.WithTokenSource(config.TokenSource(ctx)),
}
client, err := gapic.NewIamClient(ctx, options...)
if err != nil {
log.Fatalf("NewIamClient: %s", err)
}
request := &iam.SetIamPolicyRequest{
Resource: ServiceAccount,
Policy: &iam.Policy{
Version: 1,
Bindings: []*iam.Binding{
{
Role: Role,
Members: []string{Member},
},
},
},
}
policy, err := client.SetIamPolicy(ctx, request)
if err != nil {
log.Fatalf("SetIamPolicy: %s", err)
}
log.Printf("resource: %s", ServiceAccount)
log.Printf("bindings: %v", policy.Bindings)
}