github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/auth_env.go (about)

     1  package openstack
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/huaweicloud/golangsdk"
     7  )
     8  
     9  var nilOptions = golangsdk.AuthOptions{}
    10  
    11  /*
    12  AuthOptionsFromEnv fills out an identity.AuthOptions structure with the
    13  settings found on the various OpenStack OS_* environment variables.
    14  
    15  The following variables provide sources of truth: OS_AUTH_URL, OS_USERNAME,
    16  OS_PASSWORD, OS_TENANT_ID, and OS_TENANT_NAME.
    17  
    18  Of these, OS_USERNAME, OS_PASSWORD, and OS_AUTH_URL must have settings,
    19  or an error will result.  OS_TENANT_ID, OS_TENANT_NAME, OS_PROJECT_ID, and
    20  OS_PROJECT_NAME are optional.
    21  
    22  OS_TENANT_ID and OS_TENANT_NAME are mutually exclusive to OS_PROJECT_ID and
    23  OS_PROJECT_NAME. If OS_PROJECT_ID and OS_PROJECT_NAME are set, they will
    24  still be referred as "tenant" in Gophercloud.
    25  
    26  To use this function, first set the OS_* environment variables (for example,
    27  by sourcing an `openrc` file), then:
    28  
    29  	opts, err := openstack.AuthOptionsFromEnv()
    30  	provider, err := openstack.AuthenticatedClient(opts)
    31  */
    32  func AuthOptionsFromEnv() (golangsdk.AuthOptions, error) {
    33  	authURL := os.Getenv("OS_AUTH_URL")
    34  	username := os.Getenv("OS_USERNAME")
    35  	userID := os.Getenv("OS_USERID")
    36  	password := os.Getenv("OS_PASSWORD")
    37  	tenantID := os.Getenv("OS_TENANT_ID")
    38  	tenantName := os.Getenv("OS_TENANT_NAME")
    39  	domainID := os.Getenv("OS_DOMAIN_ID")
    40  	domainName := os.Getenv("OS_DOMAIN_NAME")
    41  
    42  	// If OS_PROJECT_ID is set, overwrite tenantID with the value.
    43  	if v := os.Getenv("OS_PROJECT_ID"); v != "" {
    44  		tenantID = v
    45  	}
    46  
    47  	// If OS_PROJECT_NAME is set, overwrite tenantName with the value.
    48  	if v := os.Getenv("OS_PROJECT_NAME"); v != "" {
    49  		tenantName = v
    50  	}
    51  
    52  	if authURL == "" {
    53  		err := golangsdk.ErrMissingInput{Argument: "authURL"}
    54  		return nilOptions, err
    55  	}
    56  
    57  	if username == "" && userID == "" {
    58  		err := golangsdk.ErrMissingInput{Argument: "username"}
    59  		return nilOptions, err
    60  	}
    61  
    62  	if password == "" {
    63  		err := golangsdk.ErrMissingInput{Argument: "password"}
    64  		return nilOptions, err
    65  	}
    66  
    67  	ao := golangsdk.AuthOptions{
    68  		IdentityEndpoint: authURL,
    69  		UserID:           userID,
    70  		Username:         username,
    71  		Password:         password,
    72  		TenantID:         tenantID,
    73  		TenantName:       tenantName,
    74  		DomainID:         domainID,
    75  		DomainName:       domainName,
    76  	}
    77  
    78  	return ao, nil
    79  }