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

Add data source for aws_ssm_patch_baseline #9486

Merged
merged 18 commits into from Jan 31, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
117 changes: 117 additions & 0 deletions aws/data_source_aws_ssm_patch_baseline.go
@@ -0,0 +1,117 @@
package aws

import (
"fmt"
"log"

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

func dataSourceAwsSsmPatchBaseline() *schema.Resource {
return &schema.Resource{
Read: dataAwsSsmPatchBaselineRead,
Schema: map[string]*schema.Schema{
"owner": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 255),
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 255),
},
"default_baseline": {
Type: schema.TypeBool,
Optional: true,
},
"operating_system": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice(ssmPatchOSs, false),
},
// Computed values
"description": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataAwsSsmPatchBaselineRead(d *schema.ResourceData, meta interface{}) error {
ssmconn := meta.(*AWSClient).ssmconn

filters := []*ssm.PatchOrchestratorFilter{
{
Key: aws.String("OWNER"),
Values: []*string{
aws.String(d.Get("owner").(string)),
},
},
}

if v, ok := d.GetOk("name_prefix"); ok {
filters = append(filters, &ssm.PatchOrchestratorFilter{
Key: aws.String("NAME_PREFIX"),
Values: []*string{
aws.String(v.(string)),
},
})
}

params := &ssm.DescribePatchBaselinesInput{
Filters: filters,
}

log.Printf("[DEBUG] Reading DescribePatchBaselines: %s", params)

resp, err := ssmconn.DescribePatchBaselines(params)

if err != nil {
return fmt.Errorf("Error describing SSM PatchBaselines: %s", err)
}

var filteredBaselines []*ssm.PatchBaselineIdentity
if v, ok := d.GetOk("operating_system"); ok {
for _, baseline := range resp.BaselineIdentities {
if v.(string) == *baseline.OperatingSystem {
filteredBaselines = append(filteredBaselines, baseline)
}
}
}

if v, ok := d.GetOk("default_baseline"); ok {
for _, baseline := range filteredBaselines {
if v.(bool) == aws.BoolValue(baseline.DefaultBaseline) {
filteredBaselines = []*ssm.PatchBaselineIdentity{baseline}
break
}
}
}

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

if len(filteredBaselines) > 1 {
return fmt.Errorf("Your query returned more than one result. Please try a more specific search criteria")
}

baseline := *filteredBaselines[0]

d.SetId(*baseline.BaselineId)
d.Set("name", baseline.BaselineName)
d.Set("description", baseline.BaselineDescription)
d.Set("default_baseline", baseline.DefaultBaseline)
d.Set("operating_system", baseline.OperatingSystem)

return nil
}
84 changes: 84 additions & 0 deletions aws/data_source_aws_ssm_patch_baseline_test.go
@@ -0,0 +1,84 @@
package aws

import (
"fmt"
"testing"

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

func TestAccAWSSsmPatchBaselineDataSource_existingBaseline(t *testing.T) {
resourceName := "data.aws_ssm_patch_baseline.test_existing"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckAwsSsmPatchBaselineDataSourceConfig_existingBaseline(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "name", "AWS-CentOSDefaultPatchBaseline"),
resource.TestCheckResourceAttr(resourceName, "description", "Default Patch Baseline for CentOS Provided by AWS."),
),
},
},
})
}

func TestAccAWSSsmPatchBaselineDataSource_newBaseline(t *testing.T) {
resourceName := "data.aws_ssm_patch_baseline.test_new"
rName := acctest.RandomWithPrefix("tf-bl-test")

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSSMPatchBaselineDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckAwsSsmPatchBaselineDataSourceConfig_newBaseline(rName),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrPair(resourceName, "name", "aws_ssm_patch_baseline.test_new", "name"),
resource.TestCheckResourceAttrPair(resourceName, "description", "aws_ssm_patch_baseline.test_new", "description"),
resource.TestCheckResourceAttrPair(resourceName, "operating_system", "aws_ssm_patch_baseline.test_new", "operating_system"),
),
},
},
})
}

// Test against one of the default baselines created by AWS
func testAccCheckAwsSsmPatchBaselineDataSourceConfig_existingBaseline() string {
return fmt.Sprintf(`
data "aws_ssm_patch_baseline" "test_existing" {
owner = "AWS"
name_prefix = "AWS-"
operating_system = "CENTOS"
}
`)
}

// Create a new baseline and pull it back
func testAccCheckAwsSsmPatchBaselineDataSourceConfig_newBaseline(name string) string {
return fmt.Sprintf(`
resource "aws_ssm_patch_baseline" "test_new" {
name = "%s"
operating_system = "AMAZON_LINUX_2"
description = "Test"

approval_rule {
approve_after_days = 5
patch_filter {
key = "CLASSIFICATION"
values = ["*"]
}
}
}

data "aws_ssm_patch_baseline" "test_new" {
owner = "Self"
name_prefix = "${aws_ssm_patch_baseline.test_new.name}"
operating_system = "AMAZON_LINUX_2"
}
`, name)
}
1 change: 1 addition & 0 deletions aws/provider.go
Expand Up @@ -284,6 +284,7 @@ func Provider() terraform.ResourceProvider {
"aws_sqs_queue": dataSourceAwsSqsQueue(),
"aws_ssm_document": dataSourceAwsSsmDocument(),
"aws_ssm_parameter": dataSourceAwsSsmParameter(),
"aws_ssm_patch_baseline": dataSourceAwsSsmPatchBaseline(),
"aws_storagegateway_local_disk": dataSourceAwsStorageGatewayLocalDisk(),
"aws_subnet": dataSourceAwsSubnet(),
"aws_subnet_ids": dataSourceAwsSubnetIDs(),
Expand Down
3 changes: 3 additions & 0 deletions website/aws.erb
Expand Up @@ -2892,6 +2892,9 @@
<li>
<a href="/docs/providers/aws/d/ssm_parameter.html">aws_ssm_parameter</a>
</li>
<li>
<a href="/docs/providers/aws/d/ssm_patch_baseline.html">aws_ssm_patch_baseline</a>
</li>
</ul>
</li>
<li>
Expand Down
54 changes: 54 additions & 0 deletions website/docs/d/ssm_patch_baseline.html.markdown
@@ -0,0 +1,54 @@
---
subcategory: "SSM"
layout: "aws"
page_title: "AWS: aws_ssm_patch_baseline"
description: |-
Provides an SSM Patch Baseline data source
---

# Data Source: aws_ssm_patch_baseline

Provides an SSM Patch Baseline data source. Useful if you wish to reuse the default baselines provided.

## Example Usage

To retrieve a baseline provided by AWS:

```hcl
data "aws_ssm_patch_baseline" "centos" {
owner = "AWS"
name_prefix = "AWS-"
operating_system = "CENTOS"
}
```

To retrieve a baseline on your account:

```hcl
data "aws_ssm_patch_baseline" "default_custom" {
owner = "Self"
name_prefix = "MyCustomBaseline"
default_baseline = true
operating_system = "WINDOWS"
}
```

## Argument Reference

The following arguments are supported:

* `owner` - (Required) The owner of the baseline. Valid values: `All`, `AWS`, `Self` (the current account).

* `name_prefix` - (Optional) Filter results by the baseline name prefix.

* `default_baseline` - (Optional) Filters the results against the baselines default_baseline field.

* `operating_system` - (Optional) The specified OS for the baseline.

## Attributes Reference

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

* `id` - The id of the baseline.
* `name` - The name of the baseline.
* `description` - The description of the baseline.