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 11 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
123 changes: 123 additions & 0 deletions aws/data_source_aws_ssm_patch_baseline.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
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,
ForceNew: true,
jdheyburn marked this conversation as resolved.
Show resolved Hide resolved
ValidateFunc: validation.NoZeroValues,
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
jdheyburn marked this conversation as resolved.
Show resolved Hide resolved
},
"default_baseline": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"operating_system": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},
// 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 {
var ln int
for _, baseline := range filteredBaselines {
if v.(bool) == *baseline.DefaultBaseline {
filteredBaselines[ln] = baseline
ln++
}
}
filteredBaselines = filteredBaselines[:ln]
jdheyburn marked this conversation as resolved.
Show resolved Hide resolved
}

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
}
83 changes: 83 additions & 0 deletions aws/data_source_aws_ssm_patch_baseline_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
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,
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
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,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
50 changes: 50 additions & 0 deletions aws/ssm_patch_baseline.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
jdheyburn marked this conversation as resolved.
Show resolved Hide resolved
layout: "aws"
page_title: "AWS: aws_ssm_patch_baseline"
sidebar_current: "docs-aws-datasource-ssm-patchbaseline"
description: |-
Provides a SSM Patch Baseline datasource
---

# 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.

jdheyburn marked this conversation as resolved.
Show resolved Hide resolved
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.