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

[ECS] new data-source/opentelekomcloud_compute_keypair_v2 #2326

Merged
merged 2 commits into from Sep 29, 2023
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
42 changes: 42 additions & 0 deletions docs/data-sources/compute_keypair_v2.md
@@ -0,0 +1,42 @@
---
subcategory: "Elastic Cloud Server (ECS)"
---

# opentelekomcloud_compute_keypair_v2

Use this data source to get details about Compute SSH key pairs from OpenTelekomCloud.

## Example Usage

```hcl
resource "opentelekomcloud_compute_keypair_v2" "kp_1" {
name = "key_1"
public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIALRzbIOR9HUYNwfKtII/et98eGXDJhf8YxHf9BtRdAU"
}

data "opentelekomcloud_compute_keypair_v2" "key_1" {
name = "key_1"

depends_on = [opentelekomcloud_compute_keypair_v2.kp_1]
}
```

## Argument Reference

* `name` - (Optional, ForceNew, String) The name of the keypair.

* `name_regex` - (Optional, ForceNew, String) A regex string to apply to the keypairs list.
This allows more advanced filtering not supported from the OpenTelekomCloud API.
This filtering is done locally on what OpenTelekomCloud returns.

## Attributes Reference

All the argument attributes are also exported as result attributes.

* `public_key` - It gives the information about the public key in the key pair.

* `fingerprint` - It is the fingerprint information about the key pair.

* `name` - See Argument Reference above.

* `user_id` - The user id of the owner of the key pair. Not filled by API now.
@@ -0,0 +1,81 @@
package acceptance

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/opentelekomcloud/terraform-provider-opentelekomcloud/opentelekomcloud/acceptance/common"
)

const publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIALRzbIOR9HUYNwfKtII/et98eGXDJhf8YxHf9BtRdAU"

func TestAccComputeV2KeyPairDataSource_basic(t *testing.T) {
resourceName := "data.opentelekomcloud_compute_keypair_v2.key_1"

resource.Test(t, resource.TestCase{
PreCheck: func() { common.TestAccPreCheck(t) },
ProviderFactories: common.TestAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccComputeV2KeyPairDataSourceBasic,
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeKeyPairV2DataSourceName(resourceName),
resource.TestCheckResourceAttr(resourceName, "name", "key_1"),
resource.TestCheckResourceAttr(resourceName, "public_key", publicKey),
),
},
{
Config: testAccComputeV2KeyPairDataSourceRegex,
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeKeyPairV2DataSourceName(resourceName),
resource.TestCheckResourceAttr(resourceName, "name", "key_1"),
resource.TestCheckResourceAttr(resourceName, "public_key", publicKey),
),
},
},
})
}

func testAccCheckComputeKeyPairV2DataSourceName(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("can't find compute keypair data source: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("compute keypair data source name not set")
}

return nil
}
}

var testAccComputeV2KeyPairDataSource_keytest = fmt.Sprintf(`
resource "opentelekomcloud_compute_keypair_v2" "kp_1" {
name = "key_1"
public_key = "%s"
}
`, publicKey)

var testAccComputeV2KeyPairDataSourceBasic = fmt.Sprintf(`
%s

data "opentelekomcloud_compute_keypair_v2" "key_1" {
name = "key_1"

depends_on = [opentelekomcloud_compute_keypair_v2.kp_1]
}
`, testAccComputeV2KeyPairDataSource_keytest)

var testAccComputeV2KeyPairDataSourceRegex = fmt.Sprintf(`
%s

data "opentelekomcloud_compute_keypair_v2" "key_1" {
name_regex = "^key.+"

depends_on = [opentelekomcloud_compute_keypair_v2.kp_1]
}
`, testAccComputeV2KeyPairDataSource_keytest)
1 change: 1 addition & 0 deletions opentelekomcloud/provider.go
Expand Up @@ -261,6 +261,7 @@ func Provider() *schema.Provider {
"opentelekomcloud_compute_bms_nic_v2": bms.DataSourceBMSNicV2(),
"opentelekomcloud_compute_bms_server_v2": bms.DataSourceBMSServersV2(),
"opentelekomcloud_compute_flavor_v2": ecs.DataSourceComputeFlavorV2(),
"opentelekomcloud_compute_keypair_v2": ecs.DataSourceComputeKeypairV2(),
"opentelekomcloud_compute_instance_v2": ecs.DataSourceComputeInstanceV2(),
"opentelekomcloud_compute_instances_v2": ecs.DataSourceComputeInstancesV2(),
"opentelekomcloud_csbs_backup_v1": csbs.DataSourceCSBSBackupV1(),
Expand Down
@@ -0,0 +1,117 @@
package ecs

import (
"context"
"log"
"regexp"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
golangsdk "github.com/opentelekomcloud/gophertelekomcloud"
"github.com/opentelekomcloud/gophertelekomcloud/openstack/compute/v2/extensions/keypairs"
"github.com/opentelekomcloud/terraform-provider-opentelekomcloud/opentelekomcloud/common/cfg"
"github.com/opentelekomcloud/terraform-provider-opentelekomcloud/opentelekomcloud/common/fmterr"
)

func DataSourceComputeKeypairV2() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceComputeKeypairV2Read,

Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringIsValidRegExp,
},
"fingerprint": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"public_key": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataSourceComputeKeypairV2Read(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*cfg.Config)
client, err := config.ComputeV2Client(config.GetRegion(d))
if err != nil {
return fmterr.Errorf(errCreateV2Client, err)
}

var allKeyPairs []keypairs.KeyPair
if keypairName := d.Get("name").(string); keypairName != "" {
kp, err := keypairs.Get(client, keypairName).Extract()
if err != nil {
if _, ok := err.(golangsdk.ErrDefault404); ok {
return fmterr.Errorf("no keypair found")
}
return fmterr.Errorf("unable to retrieve OpenTelekomCloud %s keypair: %w", keypairName, err)
}

allKeyPairs = append(allKeyPairs, *kp)
} else {
allPages, err := keypairs.List(client).AllPages()
if err != nil {
return fmterr.Errorf("Unable to query OpenTelekomCloud keypairs: %w", err)
}

allKeyPairs, err = keypairs.ExtractKeyPairs(allPages)
if err != nil {
return fmterr.Errorf("Unable to retrieve OpenTelekomCloud keypairs: %w", err)
}
}

var filteredKeyPairs []keypairs.KeyPair
if nameRegex, ok := d.GetOk("name_regex"); ok {
r := regexp.MustCompile(nameRegex.(string))
for _, kp := range allKeyPairs {
if r.MatchString(kp.Name) {
filteredKeyPairs = append(filteredKeyPairs, kp)
}
}
allKeyPairs = filteredKeyPairs
}

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

keypair := allKeyPairs[0]

log.Printf("[DEBUG] Retrieved opentelekoncloud_compute_keypair_v2 %s: %#v", keypair.Name, keypair)

d.SetId(keypair.Name)
mErr := multierror.Append(
d.Set("name", keypair.Name),
d.Set("user_id", keypair.UserID),
d.Set("fingerprint", keypair.Fingerprint),
d.Set("public_key", keypair.PublicKey),
)
if err := mErr.ErrorOrNil(); err != nil {
return diag.FromErr(err)
}

return nil
}
4 changes: 4 additions & 0 deletions releasenotes/notes/ds-keypair-ae3677b08dbf04b9.yaml
@@ -0,0 +1,4 @@
---
features:
- |
**New Data Source:** ``opentelekomcloud_compute_keypair_v2`` (`#2326 <https://github.com/opentelekomcloud/terraform-provider-opentelekomcloud/pull/2326>`_)