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

feat: regenerate talosconfig #167

Merged
merged 1 commit into from
Jun 27, 2024
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
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/hashicorp/terraform-plugin-framework-timeouts v0.4.1
github.com/hashicorp/terraform-plugin-framework-validators v0.12.0
github.com/hashicorp/terraform-plugin-go v0.23.0
github.com/hashicorp/terraform-plugin-log v0.9.0
github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0
github.com/hashicorp/terraform-plugin-testing v1.8.0
github.com/siderolabs/crypto v0.4.4
Expand All @@ -20,7 +21,7 @@ require (
golang.org/x/mod v0.18.0
google.golang.org/grpc v1.64.0
gopkg.in/yaml.v3 v3.0.1
k8s.io/client-go v0.30.1
k8s.io/client-go v0.30.2
)

require (
Expand Down Expand Up @@ -79,7 +80,6 @@ require (
github.com/hashicorp/logutils v1.0.0 // indirect
github.com/hashicorp/terraform-exec v0.21.0 // indirect
github.com/hashicorp/terraform-json v0.22.1 // indirect
github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect
github.com/hashicorp/terraform-registry-address v0.2.3 // indirect
github.com/hashicorp/terraform-svchost v0.1.1 // indirect
github.com/hashicorp/yamux v0.1.1 // indirect
Expand Down Expand Up @@ -136,7 +136,7 @@ require (
google.golang.org/protobuf v1.34.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/apimachinery v0.30.1 // indirect
k8s.io/apimachinery v0.30.2 // indirect
k8s.io/klog/v2 v2.120.1 // indirect
k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
Expand Down
12 changes: 6 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -457,12 +457,12 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
k8s.io/api v0.30.1 h1:kCm/6mADMdbAxmIh0LBjS54nQBE+U4KmbCfIkF5CpJY=
k8s.io/api v0.30.1/go.mod h1:ddbN2C0+0DIiPntan/bye3SW3PdwLa11/0yqwvuRrJM=
k8s.io/apimachinery v0.30.1 h1:ZQStsEfo4n65yAdlGTfP/uSHMQSoYzU/oeEbkmF7P2U=
k8s.io/apimachinery v0.30.1/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc=
k8s.io/client-go v0.30.1 h1:uC/Ir6A3R46wdkgCV3vbLyNOYyCJ8oZnjtJGKfytl/Q=
k8s.io/client-go v0.30.1/go.mod h1:wrAqLNs2trwiCH/wxxmT/x3hKVH9PuV0GGW0oDoHVqc=
k8s.io/api v0.30.2 h1:+ZhRj+28QT4UOH+BKznu4CBgPWgkXO7XAvMcMl0qKvI=
k8s.io/api v0.30.2/go.mod h1:ULg5g9JvOev2dG0u2hig4Z7tQ2hHIuS+m8MNZ+X6EmI=
k8s.io/apimachinery v0.30.2 h1:fEMcnBj6qkzzPGSVsAZtQThU62SmQ4ZymlXRC5yFSCg=
k8s.io/apimachinery v0.30.2/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc=
k8s.io/client-go v0.30.2 h1:sBIVJdojUNPDU/jObC+18tXWcTJVcwyqS9diGdWHk50=
k8s.io/client-go v0.30.2/go.mod h1:JglKSWULm9xlJLx4KCkfLLQ7XwtlbflV6uFFSHTMgVs=
k8s.io/klog/v2 v2.120.1 h1:QXU6cPEOIslTGvZaXvFWiP9VKyeet3sawzTOvdXb4Vw=
k8s.io/klog/v2 v2.120.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag=
Expand Down
10 changes: 5 additions & 5 deletions hack/release.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ project_name = "terraform-provider-talos"
github_repo = "siderolabs/terraform-provider-talos"
match_deps = "^github.com/(siderolabs/[a-zA-Z0-9-]+)$"

previous = "v0.3.2"
previous = "v0.5.0"
pre_release = true

[notes]

[notes.talos_cluster_health]
title = "Talos Cluster Health data source"
[notes.talos_machine_secrets]
title = "Talos Machine Secrets"
description = """\
`talos_cluster_health` data source has been added and the `wait` parameter from the `talos_cluster_kubeconfig` data source is now deprecated.
`talos_machine_secrets` resource now regenerates client config when the time to expiry is less than a month.
"""

[notes.updates]
title = "Component Updates"
description = """\
Talos sdk: v1.6.0-alpha.0
Talos sdk: v1.8.0-alpha.0
"""
187 changes: 184 additions & 3 deletions pkg/talos/talos_machine_secrets_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ package talos

import (
"context"
"crypto/x509"
"encoding/pem"
"os"
"time"

Expand All @@ -17,6 +19,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/siderolabs/talos/pkg/machinery/config/generate/secrets"
"github.com/siderolabs/talos/pkg/machinery/gendata"
"golang.org/x/mod/semver"
Expand All @@ -27,8 +30,16 @@ var (
_ resource.Resource = &talosMachineSecretsResource{}
_ resource.ResourceWithUpgradeState = &talosMachineSecretsResource{}
_ resource.ResourceWithImportState = &talosMachineSecretsResource{}
_ resource.ResourceWithModifyPlan = &talosMachineSecretsResource{}
)

// OverridableTimeFunc is a function that returns the current time. It is used to allow tests to override the current time.
//
//nolint:gocritic
var OverridableTimeFunc = func() time.Time {
return time.Now()
}

type talosMachineSecretsResource struct{}

type talosMachineSecretsResourceModelV0 struct {
Expand Down Expand Up @@ -298,23 +309,193 @@ func (r *talosMachineSecretsResource) Create(ctx context.Context, req resource.C
func (r *talosMachineSecretsResource) Read(_ context.Context, _ resource.ReadRequest, _ *resource.ReadResponse) {
}

func (r *talosMachineSecretsResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
// delete is a no-op
if req.Plan.Raw.IsNull() {
return
}

clientConfigurationPath := path.Root("client_configuration")

var obj types.Object

resp.Diagnostics.Append(req.State.GetAttribute(ctx, clientConfigurationPath, &obj)...)

if resp.Diagnostics.HasError() {
return
}

var clientConfigurationData clientConfiguration

diags := obj.As(ctx, &clientConfigurationData, basetypes.ObjectAsOptions{
UnhandledNullAsEmpty: true,
UnhandledUnknownAsEmpty: true,
})
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

if clientConfigurationData.CA.IsNull() || clientConfigurationData.CA.IsUnknown() {
return
}

clientCertificate := clientConfigurationData.Cert.ValueString()

clientCertificateBytes, err := base64ToBytes(clientCertificate)
if err != nil {
resp.Diagnostics.AddError("failed to decode client certificate", err.Error())

return
}

block, _ := pem.Decode(clientCertificateBytes)
if block == nil {
resp.Diagnostics.AddError("failed to decode client certificate", "failed to parse PEM block")

return
}

x509Cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
resp.Diagnostics.AddError("failed to parse client certificate", err.Error())

return
}

// check if NotAfter expires in a month
if x509Cert.NotAfter.Before(OverridableTimeFunc().AddDate(0, 1, 0)) {
tflog.Info(ctx, "client certificate expires in a month, regenerating")

resp.Diagnostics.Append(resp.Plan.SetAttribute(ctx, path.Root("client_configuration").AtName("ca_certificate"), types.StringUnknown())...)
resp.Diagnostics.Append(resp.Plan.SetAttribute(ctx, path.Root("client_configuration").AtName("client_certificate"), types.StringUnknown())...)
resp.Diagnostics.Append(resp.Plan.SetAttribute(ctx, path.Root("client_configuration").AtName("client_key"), types.StringUnknown())...)

if resp.Diagnostics.HasError() {
return
}
}
}

func (r *talosMachineSecretsResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var obj string
var talosVersion string

diags := req.Plan.GetAttribute(ctx, path.Root("talos_version"), &obj)
diags := req.Plan.GetAttribute(ctx, path.Root("talos_version"), &talosVersion)
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

// Set state to fully populated data
diags = resp.State.SetAttribute(ctx, path.Root("talos_version"), obj)
diags = resp.State.SetAttribute(ctx, path.Root("talos_version"), talosVersion)
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

clientConfigurationPath := path.Root("client_configuration")

var obj types.Object

resp.Diagnostics.Append(req.State.GetAttribute(ctx, clientConfigurationPath, &obj)...)

if resp.Diagnostics.HasError() {
return
}

var clientConfigurationData clientConfiguration

diags = obj.As(ctx, &clientConfigurationData, basetypes.ObjectAsOptions{
UnhandledNullAsEmpty: true,
UnhandledUnknownAsEmpty: true,
})
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

if clientConfigurationData.CA.IsNull() || clientConfigurationData.CA.IsUnknown() {
return
}

clientCertificate := clientConfigurationData.Cert.ValueString()

clientCertificateBytes, err := base64ToBytes(clientCertificate)
if err != nil {
resp.Diagnostics.AddError("failed to decode client certificate", err.Error())

return
}

block, _ := pem.Decode(clientCertificateBytes)
if block == nil {
resp.Diagnostics.AddError("failed to decode client certificate", "failed to parse PEM block")

return
}

x509Cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
resp.Diagnostics.AddError("failed to parse client certificate", err.Error())

return
}

// check if NotAfter expires in a month
if x509Cert.NotAfter.Before(OverridableTimeFunc().AddDate(0, 1, 0)) {
tflog.Info(ctx, "client certificate expires in a month, regenerating")

var obj types.Object

diags := req.State.Get(ctx, &obj)
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

var config talosMachineSecretsResourceModelV1

diags = obj.As(ctx, &config, basetypes.ObjectAsOptions{
UnhandledNullAsEmpty: true,
UnhandledUnknownAsEmpty: true,
})
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

secretsBundle, err := machineSecretsToSecretsBundle(config)
if err != nil {
resp.Diagnostics.AddError("failed to convert machine secrets to secrets bundle", err.Error())

return
}

if secretsBundle.Clock == nil {
secretsBundle.Clock = secrets.NewFixedClock(time.Now())
}

state, err := secretsBundleTomachineSecrets(secretsBundle)
if err != nil {
resp.Diagnostics.AddError("failed to convert secrets bundle to machine secrets", err.Error())

return
}

resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("client_configuration").AtName("ca_certificate"), &state.ClientConfiguration.CA)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("client_configuration").AtName("client_certificate"), &state.ClientConfiguration.Cert)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("client_configuration").AtName("client_key"), &state.ClientConfiguration.Key)...)

if resp.Diagnostics.HasError() {
return
}
}
}

func (r *talosMachineSecretsResource) Delete(_ context.Context, _ resource.DeleteRequest, _ *resource.DeleteResponse) {
Expand Down
47 changes: 45 additions & 2 deletions pkg/talos/talos_machine_secrets_resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,19 @@ package talos_test
import (
"fmt"
"testing"
"time"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/plancheck"
"github.com/siderolabs/talos/pkg/machinery/gendata"
"golang.org/x/mod/semver"

"github.com/siderolabs/terraform-provider-talos/pkg/talos"
)

func TestAccTalosMachineSecretsResource(t *testing.T) {
testTime := time.Now()

resource.ParallelTest(t, resource.TestCase{
IsUnitTest: true, // this is a local only resource, so can be unit tested
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Expand Down Expand Up @@ -45,9 +50,47 @@ func TestAccTalosMachineSecretsResource(t *testing.T) {
resource.TestCheckNoResourceAttr("talos_machine_secrets.this", "machine_secrets.secrets.aescbc_encryption_secret"),
),
},
// test talosconfig regeneration
{
Config: testAccTalosMachineSecretsResourceConfig(""),
PreConfig: func() {
talos.OverridableTimeFunc = func() time.Time {
return testTime.AddDate(0, 12, 5)
}
},
PlanOnly: true,
ExpectNonEmptyPlan: true,
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("talos_machine_secrets.this", "id", "machine_secrets"),
resource.TestCheckResourceAttr("talos_machine_secrets.this", "talos_version", semver.MajorMinor(gendata.VersionTag)),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.cluster.id"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.cluster.secret"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.secrets.bootstrap_token"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.secrets.secretbox_encryption_secret"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.trustdinfo.token"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.etcd.cert"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.etcd.key"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.k8s.cert"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.k8s.key"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.k8s_aggregator.cert"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.k8s_aggregator.key"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.k8s_serviceaccount.key"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.os.cert"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.certs.os.key"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "client_configuration.ca_certificate"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "client_configuration.client_certificate"),
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "client_configuration.client_key"),
resource.TestCheckNoResourceAttr("talos_machine_secrets.this", "machine_secrets.secrets.aescbc_encryption_secret"),
),
},
// test that setting the talos_version to the same value does not cause a diff
{
Config: testAccTalosMachineSecretsResourceConfig(semver.MajorMinor(gendata.VersionTag)),
PreConfig: func() {
talos.OverridableTimeFunc = func() time.Time {
return testTime
}
},
ConfigPlanChecks: resource.ConfigPlanChecks{
PreApply: []plancheck.PlanCheck{
plancheck.ExpectEmptyPlan(),
Expand Down Expand Up @@ -76,7 +119,7 @@ func TestAccTalosMachineSecretsResource(t *testing.T) {
resource.TestCheckNoResourceAttr("talos_machine_secrets.this", "machine_secrets.secrets.aescbc_encryption_secret"),
),
},
// test that setting the talos_version to a lower version causes a diff
// test that setting the talos_version to a lower version causes a diff and requires replacement
// also test that the aescbc_encryption_secret is set
{ //nolint:dupl
Config: testAccTalosMachineSecretsResourceConfig("v1.2.0"),
Expand Down Expand Up @@ -108,7 +151,7 @@ func TestAccTalosMachineSecretsResource(t *testing.T) {
resource.TestCheckResourceAttrSet("talos_machine_secrets.this", "machine_secrets.secrets.aescbc_encryption_secret"),
),
},
// test that setting the talos_version to a higher version does not cause a diff
// test that setting the talos_version to a higher version does not cause a diff and requires no replacement
// also test that the aescbc_encryption_secret is still set when upgrading
{ //nolint:dupl
Config: testAccTalosMachineSecretsResourceConfig("v1.4"),
Expand Down
Loading