Skip to content

Commit

Permalink
Merge pull request #665 from terraform-routeros/vaerh/issue660
Browse files Browse the repository at this point in the history
fix: Importing certificate and key without `routeros_file` resource
  • Loading branch information
vaerh authored Feb 19, 2025
2 parents 6c94720 + 1376755 commit f978a8d
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 23 deletions.
28 changes: 7 additions & 21 deletions examples/resources/routeros_system_certificate/resource.tf
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,12 @@ data "routeros_x509" "cert" {
-----END CERTIFICATE-----
EOT
}

resource "routeros_file" "key" {
name = "external.key"
# The lines of the certificate must not contain indentation.
contents = <<EOT
resource "routeros_system_certificate" "external" {
name = "external.crt"
common_name = data.routeros_x509.cert.common_name
import {
cert_file_content = data.routeros_x509.cert.pem
key_file_content = <<EOT
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIHeMEkGCSqGSIb3DQEFDTA8MBsGCSqGSIb3DQEFDDAOBAiy/wEW6/MglgICCAAw
HQYJYIZIAWUDBAEqBBD6v8dLA2FjPn62Xz57pcu9BIGQhclivPw1eC2b14ea58Tw
Expand All @@ -79,21 +80,6 @@ nzDdbYN6/yUiMqapW2xZaT7ZFnbEai4n9/utgtEDnfKHlZvZj2kRhvYoWrvTkt/W
Sk+abxJ+NMQoh+S5d73niu1CO8uqQjOd8BoSOurURsOh
-----END ENCRYPTED PRIVATE KEY-----
EOT
}

resource "routeros_file" "cert" {
name = "external.crt"
# Normalized certificate
contents = data.routeros_x509.cert.pem
}

resource "routeros_system_certificate" "external" {
name = "external.crt"
common_name = data.routeros_x509.cert.common_name
import {
cert_file_name = routeros_file.cert.name
key_file_name = routeros_file.key.name
passphrase = "11111111"
passphrase = "11111111"
}
depends_on = [routeros_file.key, routeros_file.cert]
}
34 changes: 34 additions & 0 deletions routeros/resource_file.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package routeros

import (
"context"
"fmt"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand Down Expand Up @@ -72,3 +76,33 @@ func ResourceFile() *schema.Resource {
Schema: resSchema,
}
}

func fileCreate(ctx context.Context, name, contents string, m interface{}) (id string, diags diag.Diagnostics) {
res, err := CreateItem(ctx, MikrotikItem{"name": name, "contents": contents}, "/file", m.(Client))
if err != nil {
ColorizedDebug(ctx, fmt.Sprintf(ErrorMsgPut, err))
diags = diag.FromErr(err)
return
}

id = res.GetID(Id)
if id == "" {
diags = diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "The file ID was not found in the response",
},
}
return
}

return
}

func fileDelete(ctx context.Context, id string, m interface{}) diag.Diagnostics {
if err := DeleteItem(&ItemId{Id, id}, "/file", m.(Client)); err != nil {
ColorizedDebug(ctx, fmt.Sprintf(ErrorMsgDelete, err))
return diag.FromErr(err)
}
return nil
}
72 changes: 70 additions & 2 deletions routeros/resource_system_certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package routeros

import (
"context"
"fmt"

"github.com/hashicorp/go-uuid"
"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"
Expand Down Expand Up @@ -40,7 +42,7 @@ func ResourceSystemCertificate() *schema.Resource {
resSchema := map[string]*schema.Schema{
MetaResourcePath: PropResourcePath("/certificate"),
MetaId: PropId(Id),
MetaSkipFields: PropSkipFields("import", "sign", "sign_via_scep"),
MetaSkipFields: PropSkipFields("import", "sign", "sign_via_scep", "cert_file_content", "key_file_content"),

"authority": {
Type: schema.TypeString,
Expand Down Expand Up @@ -127,16 +129,31 @@ func ResourceSystemCertificate() *schema.Resource {
Optional: true,
ForceNew: true,
ConflictsWith: []string{"sign", "sign_via_scep"},
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_file_content": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Certificate in PEM format.",
},
"cert_file_name": {
Type: schema.TypeString,
Required: true,
Optional: true,
ForceNew: true,
Description: "Certificate file name that will be imported.",
},
"key_file_content": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Key in PEM format.",
},
"key_file_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Key file name that will be imported.",
},
"passphrase": {
Expand Down Expand Up @@ -373,6 +390,57 @@ func ResourceSystemCertificate() *schema.Resource {
resUrl.Path += "/import"
}

if data := bl["cert_file_content"].(string); data != "" {
// Validation
if bl["cert_file_name"].(string) != "" {
return diag.Errorf("%q: conflicts with %s", "cert_file_content", "cert_file_name")
}

name, err := uuid.GenerateUUID()
if err != nil {
return diag.FromErr(err)
}

certFileId, diags := fileCreate(ctx, name, data, m)
if diags != nil {
return diags
}

ColorizedDebug(ctx, fmt.Sprintf("The certificate has been placed on file '%v'", name))

bl["cert_file_name"] = name

defer func() {
diags = fileDelete(ctx, certFileId, m)
if diags != nil {
ColorizedMessage(ctx, ERROR, "Certificate file deletion error", map[string]interface{}{"diags": diags})
}
}()
}

if data := bl["key_file_content"].(string); data != "" {
// Validation
if bl["key_file_name"].(string) != "" {
return diag.Errorf("%q: conflicts with %s", "key_file_content", "key_file_name")
}

name, err := uuid.GenerateUUID()
if err != nil {
return diag.FromErr(err)
}

bl["key_file_name"] = name

// File is deleted by the MT after import.
// https://github.com/terraform-routeros/terraform-provider-routeros/issues/660
_, diags := fileCreate(ctx, name, data, m)
if diags != nil {
return diags
}

ColorizedDebug(ctx, fmt.Sprintf("The private key has been placed on file '%v'", name))
}

params := MikrotikItem{KeyName: d.Get(KeyName).(string), "file-name": bl["cert_file_name"].(string)}
if passwd, ok := bl["passphrase"]; ok {
params["passphrase"] = passwd.(string)
Expand Down

0 comments on commit f978a8d

Please sign in to comment.