Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Data Source: azuread_client_config #229

Merged
merged 6 commits into from
Mar 12, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion azuread/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ import (
type ArmClient struct {
subscriptionID string
clientID string
objectID string
tenantID string
terraformVersion string
environment azure.Environment

authenticatedAsAServicePrincipal bool

StopContext context.Context

// azure AD clients
Expand All @@ -36,19 +39,32 @@ type ArmClient struct {
}

// getArmClient is a helper method which returns a fully instantiated *ArmClient based on the auth Config's current settings.
func getArmClient(authCfg *authentication.Config, tfVersion string) (*ArmClient, error) {
func getArmClient(authCfg *authentication.Config, tfVersion string, ctx context.Context) (*ArmClient, error) {
env, err := authentication.DetermineEnvironment(authCfg.Environment)
if err != nil {
return nil, err
}

objectID := ""
// TODO remove this when we confirm that MSI no longer returns nil with getAuthenticatedObjectID
if getAuthenticatedObjectID := authCfg.GetAuthenticatedObjectID; getAuthenticatedObjectID != nil {
v, err := getAuthenticatedObjectID(ctx)
if err != nil {
return nil, fmt.Errorf("Error getting authenticated object ID: %v", err)
}
objectID = v
}

// client declarations:
client := ArmClient{
subscriptionID: authCfg.SubscriptionID,
clientID: authCfg.ClientID,
objectID: objectID,
tenantID: authCfg.TenantID,
terraformVersion: tfVersion,
environment: *env,

authenticatedAsAServicePrincipal: authCfg.AuthenticatedAsAServicePrincipal,
}

sender := sender.BuildSender("AzureAD")
Expand Down
69 changes: 69 additions & 0 deletions azuread/data_client_config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package azuread

import (
"fmt"
"time"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func dataClientConfig() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmClientConfigRead,

Timeouts: &schema.ResourceTimeout{
Read: schema.DefaultTimeout(5 * time.Minute),
},

Schema: map[string]*schema.Schema{
"client_id": {
Type: schema.TypeString,
Computed: true,
},

"tenant_id": {
Type: schema.TypeString,
Computed: true,
},

"subscription_id": {
Type: schema.TypeString,
Computed: true,
},

"object_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataSourceArmClientConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient)
ctx := meta.(*ArmClient).StopContext

if client.authenticatedAsAServicePrincipal {
spClient := client.servicePrincipalsClient
// Application & Service Principal is 1:1 per tenant. Since we know the appId (client_id)
// here, we can query for the Service Principal whose appId matches.
filter := fmt.Sprintf("appId eq '%s'", client.clientID)
listResult, listErr := spClient.List(ctx, filter)

if listErr != nil {
return fmt.Errorf("Error listing Service Principals: %#v", listErr)
}

if listResult.Values() == nil || len(listResult.Values()) != 1 {
return fmt.Errorf("Unexpected Service Principal query result: %#v", listResult.Values())
}
}

d.SetId(time.Now().UTC().String())
d.Set("client_id", client.clientID)
d.Set("object_id", client.objectID)
d.Set("subscription_id", client.subscriptionID)
d.Set("tenant_id", client.tenantID)

return nil
}
48 changes: 48 additions & 0 deletions azuread/data_client_config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package azuread

import (
"os"
"regexp"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccClientConfigDataSource_basic(t *testing.T) {
dsn := "data.azuread_client_config.current"
clientId := os.Getenv("ARM_CLIENT_ID")
tenantId := os.Getenv("ARM_TENANT_ID")
subscriptionId := os.Getenv("ARM_SUBSCRIPTION_ID")

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckArmClientConfig_basic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dsn, "client_id", clientId),
resource.TestCheckResourceAttr(dsn, "tenant_id", tenantId),
resource.TestCheckResourceAttr(dsn, "subscription_id", subscriptionId),
testAzureRMClientConfigGUIDAttr(dsn, "object_id"),
),
},
},
})
}

func testAzureRMClientConfigGUIDAttr(name, key string) resource.TestCheckFunc {
return func(s *terraform.State) error {
r, err := regexp.Compile("^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$")
if err != nil {
return err
}

return resource.TestMatchResourceAttr(name, key, r)(s)
}
}

const testAccCheckArmClientConfig_basic = `
data "azuread_client_config" "current" { }
`
2 changes: 1 addition & 1 deletion azuread/helpers/graph/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func PasswordResourceSchema(object_type string) map[string]*schema.Schema {
Required: true,
ForceNew: true,
Sensitive: true,
ValidateFunc: validate.NoEmptyStrings,
ValidateFunc: validation.StringLenBetween(1, 863), // Encrypted secret cannot be empty and can be at most 1024 bytes.
},

"start_date": {
Expand Down
3 changes: 2 additions & 1 deletion azuread/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func Provider() terraform.ResourceProvider {
DataSourcesMap: map[string]*schema.Resource{
"azuread_application": dataApplication(),
"azuread_domains": dataDomains(),
"azuread_client_config": dataClientConfig(),
"azuread_group": dataGroup(),
"azuread_groups": dataGroups(),
"azuread_service_principal": dataServicePrincipal(),
Expand Down Expand Up @@ -120,7 +121,7 @@ func providerConfigure(p *schema.Provider) schema.ConfigureFunc {
return nil, fmt.Errorf("Error building AzureAD Client: %s", err)
}

client, err := getArmClient(config, p.TerraformVersion)
client, err := getArmClient(config, p.TerraformVersion, p.StopContext())
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion azuread/resource_application_password.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func resourceApplicationPassword() *schema.Resource {
Required: true,
ForceNew: true,
Sensitive: true,
ValidateFunc: validate.NoEmptyStrings,
ValidateFunc: validation.StringLenBetween(1, 863), // Encrypted secret cannot be empty and can be at most 1024 bytes.
},

"start_date": {
Expand Down