Skip to content

Commit

Permalink
New Data Source: aws_credentials
Browse files Browse the repository at this point in the history
Changes:
`
* **New Data Source:** `aws_credentials`
`

Output from acceptance testing:
`
make testacc TESTARGS='-run=TestAccAWSCredentials_'
==> Checking that code complies with gofmt requirements...
TF_ACC=1 go test ./aws -v -count 1 -parallel 20
-run=TestAccAWSCredentials_ -timeout 120m
=== RUN   TestAccAWSCredentials_basic
=== PAUSE TestAccAWSCredentials_basic
=== CONT  TestAccAWSCredentials_basic
--- PASS: TestAccAWSCredentials_basic (62.60s)
PASS
ok      github.com/terraform-providers/terraform-provider-aws/aws
64.457s
`
  • Loading branch information
Omarimcblack committed Nov 27, 2020
1 parent 65cbd23 commit d8bef0b
Show file tree
Hide file tree
Showing 6 changed files with 173 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .hashibot.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,7 @@ behavior "pull_request_path_labeler" "service_labels" {
"aws/awserr.go",
"aws/config.go",
"aws/*_aws_arn*",
"aws/*_aws_credentials*",
"aws/*_aws_ip_ranges*",
"aws/*_aws_partition*",
"aws/*_aws_region*",
Expand All @@ -624,6 +625,7 @@ behavior "pull_request_path_labeler" "service_labels" {
"main.go",
"website/docs/index.html.markdown",
"website/**/arn*",
"website/**/credentials*",
"website/**/ip_ranges*",
"website/**/partition*",
"website/**/region*"
Expand Down
3 changes: 3 additions & 0 deletions aws/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/accessanalyzer"
Expand Down Expand Up @@ -238,6 +239,7 @@ type AWSClient struct {
cognitoidpconn *cognitoidentityprovider.CognitoIdentityProvider
configconn *configservice.ConfigService
costandusagereportconn *costandusagereportservice.CostandUsageReportService
credentials *credentials.Credentials
dataexchangeconn *dataexchange.DataExchange
datapipelineconn *datapipeline.DataPipeline
datasyncconn *datasync.DataSync
Expand Down Expand Up @@ -475,6 +477,7 @@ func (c *Config) Client() (interface{}, error) {
cognitoidpconn: cognitoidentityprovider.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cognitoidp"])})),
configconn: configservice.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["configservice"])})),
costandusagereportconn: costandusagereportservice.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cur"])})),
credentials: sess.Config.Credentials,
dataexchangeconn: dataexchange.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["dataexchange"])})),
datapipelineconn: datapipeline.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["datapipeline"])})),
datasyncconn: datasync.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["datasync"])})),
Expand Down
58 changes: 58 additions & 0 deletions aws/data_source_aws_credentials.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package aws

import (
"fmt"
"log"

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

func dataSourceAwsCredentials() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsCredentialsRead,
Schema: map[string]*schema.Schema{
"access_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},

"secret_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},

"token": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
},
}
}

func dataSourceAwsCredentialsRead(d *schema.ResourceData, meta interface{}) error {
providerCredentials := meta.(*AWSClient).credentials

log.Printf("[DEBUG] Reading Provider Credentials")

val, err := providerCredentials.Get()
if err != nil {
return fmt.Errorf("Error getting Provider Credentials: %v", err)
}

log.Printf("[DEBUG] Received Provider Credentials: %s", val.ProviderName)

d.SetId(val.ProviderName)

if val.HasKeys() {
log.Printf("[DEBUG] Received provider has both AccessKeyID and SecretAccessKey value set")
d.Set("access_key", val.AccessKeyID)
d.Set("secret_key", val.SecretAccessKey)
}

d.Set("token", val.SessionToken)

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

import (
"fmt"
"testing"

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

func TestAccAWSCredentials_basic(t *testing.T) {
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccCheckAwsCredentialsConfig_basic,
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsCredentials("data.aws_credentials.current"),
),
},
},
})
}

func testAccCheckAwsCredentials(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Can't find credentials resource: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("credentials resource ID not set.")
}

expected, err := testAccProvider.Meta().(*AWSClient).credentials.Get()
if err != nil {
return fmt.Errorf("Error getting test Provider Credentials: %v", err)
}

if rs.Primary.Attributes["access_key"] != expected.AccessKeyID {
return fmt.Errorf("Incorrect access_key: expected %q, got %q", expected.AccessKeyID, rs.Primary.Attributes["access_key"])
}

if rs.Primary.Attributes["secret_key"] != expected.SecretAccessKey {
return fmt.Errorf("Incorrect secret_key: expected %q, got %q", expected.SecretAccessKey, rs.Primary.Attributes["secret_key"])
}

if rs.Primary.Attributes["token"] != expected.SessionToken {
return fmt.Errorf("Incorrect token: expected %q, got %q", expected.SessionToken, rs.Primary.Attributes["token"])
}

return nil
}
}

const testAccCheckAwsCredentialsConfig_basic = `
data "aws_credentials" "current" {}
`
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ func Provider() *schema.Provider {
"aws_codeartifact_repository_endpoint": dataSourceAwsCodeArtifactRepositoryEndpoint(),
"aws_cognito_user_pools": dataSourceAwsCognitoUserPools(),
"aws_codecommit_repository": dataSourceAwsCodeCommitRepository(),
"aws_credentials": dataSourceAwsCredentials(),
"aws_cur_report_definition": dataSourceAwsCurReportDefinition(),
"aws_db_cluster_snapshot": dataSourceAwsDbClusterSnapshot(),
"aws_db_event_categories": dataSourceAwsDbEventCategories(),
Expand Down
49 changes: 49 additions & 0 deletions website/docs/d/credentials.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
subcategory: ""
layout: "aws"
page_title: "AWS: aws_credentials"
description: |-
Get the credentials of the configured provider.
---

# Data Source: aws_arn

use the `aws_credentials` data source to get access to the AWS credentials of a configured provider.

~> **Note:** All attributes will be stored in
the raw state as plain-text. [Read more about sensitive data in
state](/docs/state/sensitive-data.html).

## Example Usage

```hcl
data "aws_credentials" "current" {}
output "access_key" {
value = data.aws_credentials.current.access_key
}
output "secret_key" {
sensitive = true
value = data.aws_credentials.current.secret_key
}
output "token" {
sensitive = true
value = data.aws_credentials.current.token
}
```

## Argument Reference

There are no arguments available for this data source.

## Attributes Reference

In addition to all arguments above, the following attributes are exported:

* `access_key` - The AWS access key part of the credentials.

* `secret_key` - The AWS secret access key part of the credentials.

* `token` - The AWS session token part of the credentials.

0 comments on commit d8bef0b

Please sign in to comment.