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

Create data source for aws iam roles #18585

Merged
merged 3 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
118 changes: 118 additions & 0 deletions aws/data_source_aws_iam_roles.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package aws

import ( // nosemgrep: aws-sdk-go-multiple-service-imports
"fmt"
"log"
"path/filepath" // filepath for glob matching

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

func dataSourceAwsIAMRoles() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsIAMRolesRead,

Schema: map[string]*schema.Schema{
"filter": dataSourceFiltersSchema(),
anGie44 marked this conversation as resolved.
Show resolved Hide resolved
"path_prefix": {
Type: schema.TypeString,
Optional: true,
},
"arns": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"names": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
},
}
}

func dataSourceAwsIAMRolesRead(d *schema.ResourceData, meta interface{}) error {
iamconn := meta.(*AWSClient).iamconn
req := &iam.ListRolesInput{}

if pathPrefix, hasPathPrefix := d.GetOk("path_prefix"); hasPathPrefix {
req.PathPrefix = aws.String(pathPrefix.(string))
}

filters, hasFilters := d.GetOk("filter")
filtersSet := []*ec2.Filter{}

if hasFilters {
filtersSet = buildAwsDataSourceFilters(filters.(*schema.Set))
log.Printf("[DEBUG] Has filters : %s", filtersSet)
// Only filters using the name "role-name" are currently supported
for _, f := range filtersSet {
if "role-name" != aws.StringValue(f.Name) {
return fmt.Errorf("Provided filters does not match supported names. See the documentation of this data source for supported filters.")
}
}
} else {
log.Printf("[DEBUG] No filter")
}

roles := []*iam.Role{}

err := iamconn.ListRolesPages(
req,
func(page *iam.ListRolesOutput, lastPage bool) bool {
for _, role := range page.Roles {
if hasFilters {
log.Printf("[DEBUG] Found Role '%s' to be checked against filters", *role.RoleName)
matchAllFilters := true
for _, f := range filtersSet {
for _, filterValue := range f.Values {
// must match all values
if matched, _ := filepath.Match(*filterValue, *role.RoleName); !matched {
log.Printf("[DEBUG] RoleName '%s' does not match filter '%s'", *role.RoleName, *filterValue)
matchAllFilters = false
}
}
}
if matchAllFilters {
roles = append(roles, role)
}
} else {
log.Printf("[DEBUG] Found Role '%s'", *role.RoleName)
roles = append(roles, role)
}
}
return !lastPage
},
)
if err != nil {
return fmt.Errorf("error reading IAM roles : %w", err)
}

if len(roles) == 0 {
log.Printf("[WARN] couldn't find any IAM role matching the provided parameters")
}
anGie44 marked this conversation as resolved.
Show resolved Hide resolved

arns := []string{}
names := []string{}
for _, v := range roles {
arns = append(arns, aws.StringValue(v.Arn))
names = append(names, aws.StringValue(v.RoleName))
}

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

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

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

import (
"fmt"
"regexp"
"strconv"
"testing"

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

func TestAccAWSDataSourceIAMRoles_basic(t *testing.T) {
dataSourceName := "data.aws_iam_roles.test"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, iam.EndpointsID),
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAWSDataSourceIAMRolesConfig_basic(),
Check: resource.ComposeTestCheckFunc(
// testCheckResourceAttrIsNot(dataSourceName, "names.#", "0"),
resource.TestMatchResourceAttr(dataSourceName, "names.#", regexp.MustCompile("[^0].*$")),
),
},
},
})
}

func TestAccAWSDataSourceIAMRoles_filterRoleName(t *testing.T) {
rCount := strconv.Itoa(acctest.RandIntRange(1, 4))
rName := acctest.RandomWithPrefix("tf-acc-test")
dataSourceName := "data.aws_iam_roles.test"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, iam.EndpointsID),
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAWSDataSourceIAMRolesConfig_filterByName(rCount, rName),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "names.#", rCount),
resource.TestCheckResourceAttr(dataSourceName, "arns.#", rCount),
),
},
},
})
}

func TestAccAWSDataSourceIAMRoles_pathPrefix(t *testing.T) {
rCount := strconv.Itoa(acctest.RandIntRange(1, 4))
rName := acctest.RandomWithPrefix("tf-acc-test")
rPathPrefix := acctest.RandomWithPrefix("tf-acc-path")
dataSourceName := "data.aws_iam_roles.test"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, iam.EndpointsID),
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAWSDataSourceIAMRolesConfig_pathPrefix(rCount, rName, rPathPrefix),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "names.#", rCount),
resource.TestCheckResourceAttr(dataSourceName, "arns.#", rCount),
),
},
},
})
}

func TestAccAWSDataSourceIAMRoles_pathPrefixAndFilterRoleName(t *testing.T) {
rCount := strconv.Itoa(acctest.RandIntRange(1, 4))
rName := acctest.RandomWithPrefix("tf-acc-test")
rPathPrefix := acctest.RandomWithPrefix("tf-acc-path")
dataSourceName := "data.aws_iam_roles.test"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, iam.EndpointsID),
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAWSDataSourceIAMRolesConfig_pathPrefixAndFilterRoleName(rCount, rName, rPathPrefix),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "names.#", rCount),
resource.TestCheckResourceAttr(dataSourceName, "arns.#", rCount),
),
},
},
})
}

func testAccAWSDataSourceIAMRolesConfig_basic() string {
return `
data "aws_iam_roles" "test" {}
`
}

func testAccAWSDataSourceIAMRolesConfig_filterByName(rCount string, rName string) string {
return fmt.Sprintf(`

resource "aws_iam_role" "test" {
count = %[1]s
name = "%[2]s-${count.index}-role"

assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
tags = {
Seed = %[2]q
}
}

data "aws_iam_roles" "test" {
filter {
name = "role-name"
values = ["${aws_iam_role.test[0].tags["Seed"]}-*-role"]
}
}
`, rCount, rName)
}

func testAccAWSDataSourceIAMRolesConfig_pathPrefix(rCount string, rName string, rPathPrefix string) string {
return fmt.Sprintf(`

resource "aws_iam_role" "test" {
count = %[1]s
name = "%[2]s-${count.index}-role"

assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF

path = "/%[3]s/"
}

data "aws_iam_roles" "test" {
path_prefix = aws_iam_role.test[0].path
}
`, rCount, rName, rPathPrefix)
}

func testAccAWSDataSourceIAMRolesConfig_pathPrefixAndFilterRoleName(rCount string, rName string, rPathPrefix string) string {
return fmt.Sprintf(`

resource "aws_iam_role" "test" {
count = %[1]s
name = "%[2]s-${count.index}-role"

assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF

path = "/%[3]s/"
tags = {
Seed = %[2]q
}
}

data "aws_iam_roles" "test" {
filter {
name = "role-name"
values = ["${aws_iam_role.test[0].tags["Seed"]}-*-role", "*-role"]
}
path_prefix = aws_iam_role.test[0].path
}
`, rCount, rName, rPathPrefix)
}
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ func Provider() *schema.Provider {
"aws_iam_policy": dataSourceAwsIAMPolicy(),
"aws_iam_policy_document": dataSourceAwsIamPolicyDocument(),
"aws_iam_role": dataSourceAwsIAMRole(),
"aws_iam_roles": dataSourceAwsIAMRoles(),
"aws_iam_server_certificate": dataSourceAwsIAMServerCertificate(),
"aws_iam_user": dataSourceAwsIAMUser(),
"aws_identitystore_group": dataSourceAwsIdentityStoreGroup(),
Expand Down
Loading