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

Adds aws_organizations_accounts datasource #20370

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .changelog/20370.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-data-source
aws_organizations_accounts
```
114 changes: 114 additions & 0 deletions aws/data_source_aws_organizations_accounts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package aws

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/organizations"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func dataSourceAwsOrganizationsAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsOrganizationsAccountsRead,

Schema: map[string]*schema.Schema{
"account_ids": {
Type: schema.TypeList,
Required: true,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.NoZeroValues,
},
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"email": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"joined_method": {
Type: schema.TypeString,
Computed: true,
},
"joined_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchemaComputed(),
},
},
},
},
}
}

func dataSourceAwsOrganizationsAccountsRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).organizationsconn
ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig

var account_ids = expandStringList(d.Get("account_ids").([]interface{}))

var accounts []map[string]interface{}

for _, account_id := range account_ids {
params := &organizations.DescribeAccountInput{
AccountId: aws.String(*account_id),
}

acc, err := conn.DescribeAccount(params)
if err != nil {
return fmt.Errorf("Error describing account: %w", err)
}

params_tags := &organizations.ListTagsForResourceInput{
ResourceId: aws.String(*account_id),
}

rt, err := conn.ListTagsForResource(params_tags)
valueTags := keyvaluetags.OrganizationsKeyValueTags(rt.Tags)
tags := valueTags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()
var account = map[string]interface{}{
"arn": aws.StringValue(acc.Account.Arn),
"email": aws.StringValue(acc.Account.Email),
"name": aws.StringValue(acc.Account.Name),
"status": aws.StringValue(acc.Account.Status),
"joined_method": aws.StringValue(acc.Account.JoinedMethod),
"joined_timestamp": aws.TimeValue(acc.Account.JoinedTimestamp).Format(time.RFC3339),
"tags": tags,
}

accounts = append(accounts, account)
}

if err := d.Set("accounts", accounts); err != nil {
return fmt.Errorf("error setting accounts: %w", err)
}

d.SetId(meta.(*AWSClient).accountid)

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

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/organizations"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func testAccDataSourceAwsOrganizationsAccounts_basic(t *testing.T) {
dataSourceName := "data.aws_organizations_accounts.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, organizations.EndpointsID),
ProviderFactories: testAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccCheckAwsOrganizationAccountResourceOnlyConfig(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "accounts.#", "1"),
resource.TestCheckResourceAttrSet(dataSourceName, "accounts.0.arn"),
resource.TestCheckResourceAttrSet(dataSourceName, "accounts.0.joined_method"),
testAccCheckResourceAttrRfc3339(dataSourceName, "accounts.0.joined_timestamp"),
resource.TestCheckResourceAttrSet(dataSourceName, "accounts.0.name"),
resource.TestCheckResourceAttrSet(dataSourceName, "accounts.0.email"),
resource.TestCheckResourceAttrSet(dataSourceName, "accounts.0.status"),
resource.TestCheckResourceAttrSet(dataSourceName, "accounts.0.tags.%"),
),
},
},
})
}

func testAccCheckAwsOrganizationAccountResourceOnlyConfig() string {
return fmt.Sprintf(`
data "aws_organizations_organization" "test" { }
data "aws_organizations_accounts" "test" { account_ids = [ data.aws_organizations_organization.test.accounts[0].id] }
`)
}
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ func Provider() *schema.Provider {
"aws_organizations_delegated_administrators": dataSourceAwsOrganizationsDelegatedAdministrators(),
"aws_organizations_delegated_services": dataSourceAwsOrganizationsDelegatedServices(),
"aws_organizations_organization": dataSourceAwsOrganizationsOrganization(),
"aws_organizations_accounts": dataSourceAwsOrganizationsAccounts(),
"aws_organizations_organizational_units": dataSourceAwsOrganizationsOrganizationalUnits(),
"aws_outposts_outpost": dataSourceAwsOutpostsOutpost(),
"aws_outposts_outpost_instance_type": dataSourceAwsOutpostsOutpostInstanceType(),
Expand Down
7 changes: 4 additions & 3 deletions aws/resource_aws_organizations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ func TestAccAWSOrganizations_serial(t *testing.T) {
"DataSource": testAccDataSourceAwsOrganizationsOrganization_basic,
},
"Account": {
"basic": testAccAwsOrganizationsAccount_basic,
"ParentId": testAccAwsOrganizationsAccount_ParentId,
"Tags": testAccAwsOrganizationsAccount_Tags,
"basic": testAccAwsOrganizationsAccount_basic,
"ParentId": testAccAwsOrganizationsAccount_ParentId,
"Tags": testAccAwsOrganizationsAccount_Tags,
"DataSource": testAccDataSourceAwsOrganizationsAccounts_basic,
},
"OrganizationalUnit": {
"basic": testAccAwsOrganizationsOrganizationalUnit_basic,
Expand Down
48 changes: 48 additions & 0 deletions website/docs/d/organizations_accounts.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
subcategory: "Organizations"
layout: "aws"
page_title: "AWS: aws_organizations_accounts"
description: |-
Get all the given accounts info (including tags) owned by the current organization that the user's account belongs to
---

# Data Source: aws_organizations_accounts

Get all the given accounts info (including tags) owned by the current organization that the user's account belongs to.
This datasource will be very useful in multi-account setups.

~> **Note:** Account info retrieval must be done from the organization's master account.

!> **WARNING:** For very large multi-account setup this will perform a large number of API requests.

## Example Usage

### List all given account arns for the organization

```terraform
data "aws_organizations_accounts" "example" {}

output "account_ids" {
value = data.aws_organizations_accounts.example.accounts[*].arn
}
```

## Argument Reference

The following argument is supported:

* `account_ids` - (Required) The accounts ID to fetch info from.

## Attributes Reference

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

* `accounts` - List of fetched accounts. All elements have these attributes:
* `arn` - ARN of the account
* `email` - Email of the account
* `id` - Identifier of the account
* `name` - Name of the account
* `status` - Current status of the account
* `joined_method` - Method used to create the account
* `joined_timestamp` - Account creation timestamp
* `tags` - Key-value map of account tags.