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: aws_security_groups #2947

Merged
merged 1 commit into from
Jun 27, 2018
Merged
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
98 changes: 98 additions & 0 deletions aws/data_source_aws_security_groups.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package aws

import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"log"
)

func dataSourceAwsSecurityGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsSecurityGroupsRead,

Schema: map[string]*schema.Schema{
"filter": dataSourceFiltersSchema(),
"tags": tagsSchemaComputed(),

"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vpc_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}

func dataSourceAwsSecurityGroupsRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
req := &ec2.DescribeSecurityGroupsInput{}

filters, filtersOk := d.GetOk("filter")
tags, tagsOk := d.GetOk("tags")

if !filtersOk && !tagsOk {
return fmt.Errorf("One of filters or tags must be assigned")
}

if filtersOk {
req.Filters = append(req.Filters,
buildAwsDataSourceFilters(filters.(*schema.Set))...)
}
if tagsOk {
req.Filters = append(req.Filters, buildEC2TagFilterList(
tagsFromMap(tags.(map[string]interface{})),
)...)
}

log.Printf("[DEBUG] Reading Security Groups with request: %s", req)

var ids, vpc_ids []string
nextToken := ""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new variable and logic surrounding it is extraneous, you can directly map the new resp.NextToken onto req.NextToken, e.g.

for {
  resp, err := conn.DescribeSecurityGroups(req)
  if err != nil {
    return fmt.Errorf("error reading security groups: %s", err)
  }
  for _, sg := range resp.SecurityGroups {
    ids = append(ids, aws.StringValue(sg.GroupId))
    vpc_ids = append(vpc_ids, aws.StringValue(sg.VpcId))
  }
  if resp.NextToken == nil {
    break
  }
  req.NextToken = resp.NextToken
}

for {
if nextToken != "" {
req.NextToken = aws.String(nextToken)
}

resp, err := conn.DescribeSecurityGroups(req)
if err != nil {
return err
}

for _, sg := range resp.SecurityGroups {
ids = append(ids, *sg.GroupId)
vpc_ids = append(vpc_ids, *sg.VpcId)
}

if resp.NextToken == nil {
break
}
nextToken = *resp.NextToken
}

if len(ids) < 1 {
return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
}

log.Printf("[DEBUG] Found %d securuity groups via given filter: %s", len(ids), req)

d.SetId(resource.UniqueId())
err := d.Set("ids", ids)
if err != nil {
return err
}

err = d.Set("vpc_ids", vpc_ids)
if err != nil {
return err
}

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

import (
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"testing"
)

func TestAccDataSourceAwsSecurityGroups_tag(t *testing.T) {
rInt := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsSecurityGroupsConfig_tag(rInt),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.aws_security_groups.by_tag", "ids.#", "3"),
resource.TestCheckResourceAttr("data.aws_security_groups.by_tag", "vpc_ids.#", "3"),
),
},
},
})
}

func TestAccDataSourceAwsSecurityGroups_filter(t *testing.T) {
rInt := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsSecurityGroupsConfig_filter(rInt),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.aws_security_groups.by_filter", "ids.#", "3"),
resource.TestCheckResourceAttr("data.aws_security_groups.by_filter", "vpc_ids.#", "3"),
),
},
},
})
}

func testAccDataSourceAwsSecurityGroupsConfig_tag(rInt int) string {
return fmt.Sprintf(`
resource "aws_vpc" "test_tag" {
cidr_block = "172.16.0.0/16"
tags {
Name = "terraform-testacc-security-group-data-source"
}
}

resource "aws_security_group" "test" {
count = 3
vpc_id = "${aws_vpc.test_tag.id}"
name = "tf-%[1]d-${count.index}"
tags {
Seed = "%[1]d"
}
}

data "aws_security_groups" "by_tag" {
tags {
Seed = "${aws_security_group.test.0.tags["Seed"]}"
}
}
`, rInt)
}

func testAccDataSourceAwsSecurityGroupsConfig_filter(rInt int) string {
return fmt.Sprintf(`
resource "aws_vpc" "test_filter" {
cidr_block = "172.16.0.0/16"
tags {
Name = "terraform-testacc-security-group-data-source"
}
}

resource "aws_security_group" "test" {
count = 3
vpc_id = "${aws_vpc.test_filter.id}"
name = "tf-%[1]d-${count.index}"
tags {
Seed = "%[1]d"
}
}

data "aws_security_groups" "by_filter" {
filter {
name = "vpc-id"
values = ["${aws_vpc.test_filter.id}"]
}
filter {
name = "group-name"
values = ["tf-${aws_security_group.test.0.tags["Seed"]}-*"]
}
}
`, rInt)
}
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ func Provider() terraform.ResourceProvider {
"aws_subnet": dataSourceAwsSubnet(),
"aws_subnet_ids": dataSourceAwsSubnetIDs(),
"aws_security_group": dataSourceAwsSecurityGroup(),
"aws_security_groups": dataSourceAwsSecurityGroups(),
"aws_vpc": dataSourceAwsVpc(),
"aws_vpc_endpoint": dataSourceAwsVpcEndpoint(),
"aws_vpc_endpoint_service": dataSourceAwsVpcEndpointService(),
Expand Down
3 changes: 3 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,9 @@
<li<%= sidebar_current("docs-aws-datasource-security-group") %>>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't expect most folks to know this, but an odd side effect of having the singular and plural data sources is that both entries will be highlighted in the sidebar if you are on the singular data source page since the sidebar_current prefix matches both. Our current convention is to go back to the singular data source and append -x to the sidebar_current in both the sidebar and singular data source page.

<a href="/docs/providers/aws/d/security_group.html">aws_security_group</a>
</li>
<li<%= sidebar_current("docs-aws-datasource-security-groups") %>>
<a href="/docs/providers/aws/d/security_groups.html">aws_security_group</a>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo 😎 : missing s in data source name

</li>
<li<%= sidebar_current("docs-aws-datasource-sns-topic") %>>
<a href="/docs/providers/aws/d/sns_topic.html">aws_sns_topic</a>
</li>
Expand Down
52 changes: 52 additions & 0 deletions website/docs/d/security_groups.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
layout: "aws"
page_title: "AWS: aws_security_groups"
sidebar_current: "docs-aws-datasource-security-groups"
description: |-
Get information about a set of Security Groups.
---

# Data Source: aws_security_groups

Use this data source to get IDs and VPC membership of Security Groups that are created
outside of Terraform.

## Example Usage
```hcl
data "aws_security_groups" "test" {
tags {
Application = "k8s",
Environment = "dev"
}
}
```

```hcl
data "aws_security_groups" "test" {
filter {
name = "group-name"
values = ["*nodes*"]
}
filter {
name = "vpc-id"
values = ["${var.vpc_id}"]
}
}
```

## Argument Reference

* `tags` - (Optional) A mapping of tags, each pair of which must exactly match for
desired security groups.

* `filter` - (Optional) One or more name/value pairs to use as filters. There are
several valid keys, for a full reference, check out
[describe-security-groups in the AWS CLI reference][1].

## Attributes Reference

* `ids` - IDs of the matches security groups.
* `vpc_ids` - The VPC IDs of the matched security groups. The data source's tag or filter *will span VPCs*
unless the `vpc-id` filter is also used.

[1]: https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html