This commit is contained in:
asteam
2024-07-25 14:33:38 +03:00
commit 6f40af6a5f
946 changed files with 98335 additions and 0 deletions

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8ciList{}
)
func NewDataSourceK8ciList() datasource.DataSource {
return &dataSourceK8ciList{}
}
// dataSourceK8ciList is the data source implementation.
type dataSourceK8ciList struct {
client *decort.DecortClient
}
func (d *dataSourceK8ciList) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
tflog.Info(ctx, "Start read data source k8ci list")
// Read Terraform configuration data into the model
var state models.K8ciListModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8ci list state")
return
}
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8ciList(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8ci list")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8ci list")
}
func (d *dataSourceK8ciList) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8ciList(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8ciList) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8ci_list"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8ciList) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8S{}
)
func NewDataSourceK8S() datasource.DataSource {
return &dataSourceK8S{}
}
// dataSourceK8S is the data source implementation.
type dataSourceK8S struct {
client *decort.DecortClient
}
func (d *dataSourceK8S) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
// Read Terraform configuration data into the model
var state models.RecordK8SDataSourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8s state")
return
}
tflog.Info(ctx, "Start read data source k8s", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8s(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s_cp cluster")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8s", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
}
func (d *dataSourceK8S) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8S(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8S) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8S) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8SComputes{}
)
func NewDataSourceK8SComputes() datasource.DataSource {
return &dataSourceK8SComputes{}
}
// dataSourceK8SComputes is the data source implementation.
type dataSourceK8SComputes struct {
client *decort.DecortClient
}
func (d *dataSourceK8SComputes) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
// Read Terraform configuration data into the model
var state models.K8SComputesModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8s computes state")
return
}
tflog.Info(ctx, "Start read data source k8s computes", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8sComputes(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s computes cluster")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8s computes", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
}
func (d *dataSourceK8SComputes) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8SComputes(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8SComputes) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_computes"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8SComputes) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8SList{}
)
func NewDataSourceK8SList() datasource.DataSource {
return &dataSourceK8SList{}
}
// dataSourceK8SList is the data source implementation.
type dataSourceK8SList struct {
client *decort.DecortClient
}
func (d *dataSourceK8SList) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
tflog.Info(ctx, "Start read data source k8s list")
// Read Terraform configuration data into the model
var state models.K8SListModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8s list state")
return
}
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8sList(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s list")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8s list")
}
func (d *dataSourceK8SList) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8SList(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8SList) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_list"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8SList) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8SListDeleted{}
)
func NewDataSourceK8SListDeleted() datasource.DataSource {
return &dataSourceK8SListDeleted{}
}
// dataSourceK8SListDeleted is the data source implementation.
type dataSourceK8SListDeleted struct {
client *decort.DecortClient
}
func (d *dataSourceK8SListDeleted) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
tflog.Info(ctx, "Start read data source k8s list deleted")
// Read Terraform configuration data into the model
var state models.K8SListDeletedModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8s list deleted state")
return
}
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8sListDeleted(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s list deleted")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8s list deleted")
}
func (d *dataSourceK8SListDeleted) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8SListDeleted(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8SListDeleted) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_list_deleted"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8SListDeleted) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8SWg{}
)
func NewDataSourceK8SWg() datasource.DataSource {
return &dataSourceK8SWg{}
}
// dataSourceK8SWg is the data source implementation.
type dataSourceK8SWg struct {
client *decort.DecortClient
}
func (d *dataSourceK8SWg) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
// Read Terraform configuration data into the model
var state models.K8SWgModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8s wg state")
return
}
tflog.Info(ctx, "Start read data source k8s wg", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WorkerGroupID.ValueInt64()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8sWg(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s wg")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8s wg", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WorkerGroupID.ValueInt64()})
}
func (d *dataSourceK8SWg) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8SWg(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8SWg) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_wg"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8SWg) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8SWgCloudInit{}
)
func NewDataSourceK8SWgCloudInit() datasource.DataSource {
return &dataSourceK8SWgCloudInit{}
}
// dataSourceK8SWgCloudInit is the data source implementation.
type dataSourceK8SWgCloudInit struct {
client *decort.DecortClient
}
func (d *dataSourceK8SWgCloudInit) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
// Read Terraform configuration data into the model
var state models.RecordK8SWgCloudInitDataSourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8s wg cloud init state")
return
}
tflog.Info(ctx, "Start read data source k8s wg cloud init", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WgId.ValueInt64()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8sWgCloudInit(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s wg cloud init")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8s wg cloud init", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WgId.ValueInt64()})
}
func (d *dataSourceK8SWgCloudInit) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8SWgCloudInit(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8SWgCloudInit) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_wg_cloud_init"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8SWgCloudInit) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,88 @@
package k8s
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceK8SWgList{}
)
func NewDataSourceK8SWgList() datasource.DataSource {
return &dataSourceK8SWgList{}
}
// dataSourceK8SWgList is the data source implementation.
type dataSourceK8SWgList struct {
client *decort.DecortClient
}
func (d *dataSourceK8SWgList) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
tflog.Info(ctx, "Start read data source k8s wg list")
// Read Terraform configuration data into the model
var state models.K8SWgListModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source k8s wg list state")
return
}
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceK8sWgList(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s wg list")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source k8s wg list")
}
func (d *dataSourceK8SWgList) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceK8SWgList(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceK8SWgList) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_wg_list"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceK8SWgList) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,77 @@
package flattens
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8ci"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func DataSourceK8ciList(ctx context.Context, state *models.K8ciListModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8ciList")
diags := diag.Diagnostics{}
k8ciList, err := utilities.K8ciListCheckPresence(ctx, state, c)
if err != nil {
diags.AddError("Error get k8ci list info", err.Error())
return diags
}
id := uuid.New()
*state = models.K8ciListModel{
ByID: state.ByID,
Name: state.Name,
Status: state.Status,
WorkerDriver: state.WorkerDriver,
MasterDriver: state.MasterDriver,
NetworkPlugins: state.NetworkPlugins,
IncludeDisabled: state.IncludeDisabled,
SortBy: state.SortBy,
Page: state.Page,
Size: state.Size,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
Items: flattenK8ciItems(ctx, k8ciList),
EntryCount: types.Int64Value(int64(k8ciList.EntryCount)),
}
tflog.Info(ctx, "End FlattenDataSourceK8ciList")
return nil
}
func flattenK8ciItems(ctx context.Context, data *k8ci.ListK8CI) []models.ItemInListK8ciModel {
tflog.Info(ctx, "Start flattenK8ciItems")
var diags diag.Diagnostics
res := make([]models.ItemInListK8ciModel, 0, len(data.Data))
for _, item := range data.Data {
temp := models.ItemInListK8ciModel{
CreatedTime: types.Int64Value(int64(item.CreatedTime)),
Description: types.StringValue(item.Description),
K8CIID: types.Int64Value(int64(item.ID)),
LBImageID: types.Int64Value(int64(item.LBImageID)),
K8CIName: types.StringValue(item.Name),
Status: types.StringValue(item.Status),
Version: types.StringValue(item.Version),
}
temp.NetworkPlugins, diags = types.ListValueFrom(ctx, types.StringType, item.NetworkPlugins)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flatten NetworkPlugins", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenK8ciItems")
return res
}

View File

@@ -0,0 +1,235 @@
package flattens
import (
"context"
"fmt"
"strings"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func DataSourceK8s(ctx context.Context, state *models.RecordK8SDataSourceModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8s", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
diags := diag.Diagnostics{}
k8SID := uint64(state.K8SID.ValueInt64())
cluster, err := utilities.K8SCPResourceCheckPresence(ctx, k8SID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about cluster with ID %d", k8SID), err.Error())
return diags
}
k8sList, err := utilities.K8sListForResourceCheckPresence(ctx, k8SID, c)
if err != nil || len(k8sList.Data) == 0 {
diags.AddError(fmt.Sprintf("Cluster with ID %d not found in List", k8SID), err.Error())
return diags
}
masterComputeList := make([]*compute.RecordCompute, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
workersComputeList := make([]*compute.RecordCompute, 0, len(cluster.K8SGroups.Workers))
for _, masterNode := range cluster.K8SGroups.Masters.DetailedInfo {
compute, err := utilities.ComputeCheckPresence(ctx, masterNode.ID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about masterNode with ID %d", masterNode.ID), err.Error())
return diags
}
masterComputeList = append(masterComputeList, compute)
}
for _, worker := range cluster.K8SGroups.Workers {
for _, info := range worker.DetailedInfo {
compute, err := utilities.ComputeCheckPresence(ctx, info.ID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about workerNode with ID %d", info.ID), err.Error())
return diags
}
workersComputeList = append(workersComputeList, compute)
}
}
id := uuid.New()
*state = models.RecordK8SDataSourceModel{
K8SID: state.K8SID,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
ACL: flattenACLDataSource(ctx, &cluster.ACL),
AccountID: types.Int64Value(int64(cluster.AccountID)),
AccountName: types.StringValue(cluster.AccountName),
BServiceID: types.Int64Value(int64(cluster.BServiceID)),
K8CI: types.Int64Value(int64(cluster.CIID)),
CreatedBy: types.StringValue(cluster.CreatedBy),
CreatedTime: types.Int64Value(int64(cluster.CreatedTime)),
DeletedBy: types.StringValue(cluster.DeletedBy),
DeletedTime: types.Int64Value(int64(cluster.DeletedTime)),
K8CIName: types.StringValue(cluster.K8CIName),
Masters: flattenMasterGroup(ctx, &cluster.K8SGroups.Masters, masterComputeList),
Workers: flattenK8sGroup(ctx, &cluster.K8SGroups.Workers, workersComputeList),
LBID: types.Int64Value(int64(cluster.LBID)),
Name: types.StringValue(cluster.Name),
NetworkPlugin: types.StringValue(cluster.NetworkPlugin),
RGID: types.Int64Value(int64(cluster.RGID)),
RGName: types.StringValue(cluster.RGName),
Status: types.StringValue(cluster.Status),
TechStatus: types.StringValue(cluster.TechStatus),
UpdatedBy: types.StringValue(cluster.UpdatedBy),
UpdatedTime: types.Int64Value(int64(cluster.UpdatedTime)),
VinsId: types.Int64Value(int64(k8sList.Data[0].VINSID)),
}
if cluster.LBID != 0 {
lb, err := c.CloudAPI().LB().Get(ctx, lb.GetRequest{LBID: cluster.LBID})
if err != nil {
tflog.Error(ctx, fmt.Sprintf("Cannot get info about LB with ID %d", cluster.LBID)+err.Error())
}
state.ExtNetID = types.Int64Value(int64(lb.ExtNetID))
state.LBIP = types.StringValue(lb.PrimaryNode.FrontendIP)
}
kubeconfig, err := c.CloudAPI().K8S().GetConfig(ctx, k8s.GetConfigRequest{K8SID: k8SID})
if err != nil {
tflog.Error(ctx, "Could not get kubeconfig:"+err.Error())
}
state.Kubeconfig = types.StringValue(kubeconfig)
tflog.Info(ctx, "End FlattenDataSourceK8s", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
return nil
}
func flattenMasterGroup(ctx context.Context, mastersGroup *k8s.MasterGroup, masters []*compute.RecordCompute) *models.MasterGroupDataSourceModel {
tflog.Info(ctx, "Start flattenMasterGroup")
res := models.MasterGroupDataSourceModel{
CPU: types.Int64Value(int64(mastersGroup.CPU)),
DetailedInfo: flattenDetailedInfoDataSource(ctx, &mastersGroup.DetailedInfo, masters),
Disk: types.Int64Value(int64(mastersGroup.Disk)),
MasterGroupId: types.Int64Value(int64(mastersGroup.ID)),
MasterGroupName: types.StringValue(mastersGroup.Name),
Num: types.Int64Value(int64(mastersGroup.Num)),
RAM: types.Int64Value(int64(mastersGroup.RAM)),
}
tflog.Info(ctx, "End flattenMasterGroup")
return &res
}
func flattenK8sGroup(ctx context.Context, k8SGroupList *k8s.ListK8SGroups, workers []*compute.RecordCompute) []models.ItemK8SGroupDataSourceModel {
tflog.Info(ctx, "Start flattenK8sGroup")
res := make([]models.ItemK8SGroupDataSourceModel, 0, len(*k8SGroupList))
var diags diag.Diagnostics
for _, k8sGroup := range *k8SGroupList {
labels := make([]string, 0)
for _, label := range k8sGroup.Labels {
if strings.HasPrefix(label, "workersGroupName") {
continue
}
labels = append(labels, label)
}
temp := models.ItemK8SGroupDataSourceModel{
CPU: types.Int64Value(int64(k8sGroup.CPU)),
DetailedInfo: flattenDetailedInfoDataSource(ctx, &k8sGroup.DetailedInfo, workers),
Disk: types.Int64Value(int64(k8sGroup.Disk)),
WorkerGroupID: types.Int64Value(int64(k8sGroup.ID)),
WorkerGroupName: types.StringValue(k8sGroup.Name),
Num: types.Int64Value(int64(k8sGroup.Num)),
RAM: types.Int64Value(int64(k8sGroup.RAM)),
}
temp.Annotations, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Annotations)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenAnnotations", diags))
}
temp.Labels, diags = types.ListValueFrom(ctx, types.StringType, labels)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenLabels", diags))
}
temp.Taints, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Taints)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenTaints", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenK8sGroup")
return res
}
func flattenDetailedInfoDataSource(ctx context.Context, di *k8s.ListDetailedInfo, computes []*compute.RecordCompute) []models.ItemDetailedInfoDataSourceModel {
tflog.Info(ctx, "Start flattenDetailedInfoDataSource")
res := make([]models.ItemDetailedInfoDataSourceModel, 0, len(*di))
for i, detailedInfo := range *di {
temp := models.ItemDetailedInfoDataSourceModel{
ComputeId: types.Int64Value(int64(detailedInfo.ID)),
Name: types.StringValue(detailedInfo.Name),
Status: types.StringValue(detailedInfo.Status),
TechStatus: types.StringValue(detailedInfo.TechStatus),
Interfaces: flattenInterfacesDataSource(ctx, &computes[i].Interfaces),
NatableVinsIp: types.StringValue(computes[i].NatableVINSIP),
NatableVinsNetwork: types.StringValue(computes[i].NatableVINSNetwork),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenDetailedInfoDataSource")
return res
}
func flattenInterfacesDataSource(ctx context.Context, interfaces *compute.ListInterfaces) []models.ItemInterfacesDataSourceModel {
tflog.Info(ctx, "Start flattenInterfacesDataSource")
res := make([]models.ItemInterfacesDataSourceModel, 0, len(*interfaces))
for _, interfaceCompute := range *interfaces {
temp := models.ItemInterfacesDataSourceModel{
DefGw: types.StringValue(interfaceCompute.DefGW),
IpAddress: types.StringValue(interfaceCompute.IPAddress),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenInterfacesDataSource")
return res
}
func flattenACLDataSource(ctx context.Context, acl *k8s.RecordACL) *models.RecordACLDataSourceModel {
tflog.Info(ctx, "Start flattenACLDataSource")
res := models.RecordACLDataSourceModel{
AccountACL: flattenACLItemsDataSource(ctx, &acl.AccountACL),
K8SACL: flattenACLItemsDataSource(ctx, &acl.K8SACL),
RGACL: flattenACLItemsDataSource(ctx, &acl.RGACL),
}
tflog.Info(ctx, "End flattenACLDataSource")
return &res
}
func flattenACLItemsDataSource(ctx context.Context, item *k8s.ListACL) []models.ItemACLDataSourceModel {
tflog.Info(ctx, "Start flattenACLItemsDataSource")
res := make([]models.ItemACLDataSourceModel, 0, len(*item))
for _, aclItem := range *item {
temp := models.ItemACLDataSourceModel{
Explicit: types.BoolValue(aclItem.Explicit),
GUID: types.StringValue(aclItem.GUID),
Right: types.StringValue(aclItem.Right),
Status: types.StringValue(aclItem.Status),
Type: types.StringValue(aclItem.Type),
UserGroupID: types.StringValue(aclItem.UserGroupID),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenACLItemsDataSource")
return res
}

View File

@@ -0,0 +1,81 @@
package flattens
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func DataSourceK8sComputes(ctx context.Context, state *models.K8SComputesModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8sComputes", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
diags := diag.Diagnostics{}
k8SID := uint64(state.K8SID.ValueInt64())
cluster, err := utilities.K8SCPResourceCheckPresence(ctx, k8SID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about cluster with ID %d", k8SID), err.Error())
return diags
}
id := uuid.New()
*state = models.K8SComputesModel{
K8SID: state.K8SID,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
Masters: flattenMasterComputes(ctx, cluster),
Workers: flattenWorkerComputes(ctx, cluster),
}
tflog.Info(ctx, "End FlattenDataSourceK8sComputes", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
return nil
}
func flattenMasterComputes(ctx context.Context, cluster *k8s.RecordK8S) []models.ItemComputeModel {
tflog.Info(ctx, "Start flattenMasterComputes")
res := make([]models.ItemComputeModel, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
for _, detailedInfo := range cluster.K8SGroups.Masters.DetailedInfo {
temp := models.ItemComputeModel{
ComputeId: types.Int64Value(int64(detailedInfo.ID)),
Name: types.StringValue(detailedInfo.Name),
GroupName: types.StringValue(cluster.K8SGroups.Masters.Name),
Status: types.StringValue(detailedInfo.Status),
TechStatus: types.StringValue(detailedInfo.TechStatus),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenMasterComputes")
return res
}
func flattenWorkerComputes(ctx context.Context, cluster *k8s.RecordK8S) []models.ItemComputeModel {
tflog.Info(ctx, "Start flattenWorkerComputes")
res := make([]models.ItemComputeModel, 0, len(cluster.K8SGroups.Workers))
for _, worker := range cluster.K8SGroups.Workers {
for _, comp := range worker.DetailedInfo {
temp := models.ItemComputeModel{
ComputeId: types.Int64Value(int64(comp.ID)),
Name: types.StringValue(comp.Name),
GroupName: types.StringValue(worker.Name),
Status: types.StringValue(comp.Status),
TechStatus: types.StringValue(comp.TechStatus),
}
res = append(res, temp)
}
}
tflog.Info(ctx, "End flattenWorkerComputes")
return res
}

View File

@@ -0,0 +1,162 @@
package flattens
import (
"context"
"fmt"
"strings"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func DataSourceK8sList(ctx context.Context, state *models.K8SListModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8sList")
diags := diag.Diagnostics{}
k8sList, err := utilities.K8sListCheckPresence(ctx, state, c)
if err != nil {
diags.AddError("Error get k8s list info", err.Error())
return diags
}
id := uuid.New()
*state = models.K8SListModel{
ByID: state.ByID,
Name: state.Name,
IPAddress: state.IPAddress,
RGID: state.RGID,
LBID: state.LBID,
BasicServiceID: state.BasicServiceID,
Status: state.Status,
TechStatus: state.TechStatus,
IncludeDeleted: state.IncludeDeleted,
SortBy: state.SortBy,
Page: state.Page,
Size: state.Size,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
Items: flattenItems(ctx, k8sList),
EntryCount: types.Int64Value(int64(k8sList.EntryCount)),
}
tflog.Info(ctx, "End FlattenDataSourceK8sList")
return nil
}
func flattenItems(ctx context.Context, data *k8s.ListK8SClusters) []models.ItemInListK8SModel {
tflog.Info(ctx, "Start flattenItems")
var diags diag.Diagnostics
res := make([]models.ItemInListK8SModel, 0, len(data.Data))
for _, item := range data.Data {
temp := models.ItemInListK8SModel{
AccountID: types.Int64Value(int64(item.AccountID)),
AccountName: types.StringValue(item.AccountName),
BServiceID: types.Int64Value(int64(item.BServiceID)),
CIID: types.Int64Value(int64(item.CIID)),
CreatedBy: types.StringValue(item.CreatedBy),
CreatedTime: types.Int64Value(int64(item.CreatedTime)),
DeletedBy: types.StringValue(item.DeletedBy),
DeletedTime: types.Int64Value(int64(item.DeletedTime)),
Description: types.StringValue(item.Description),
ExtNetID: types.Int64Value(int64(item.ExtNetID)),
GID: types.Int64Value(int64(item.GID)),
GUID: types.Int64Value(int64(item.GUID)),
K8SID: types.Int64Value(int64(item.ID)),
LBID: types.Int64Value(int64(item.LBID)),
Milestones: types.Int64Value(int64(item.Milestones)),
Name: types.StringValue(item.Name),
NetworkPlugin: types.StringValue(item.NetworkPlugin),
RGID: types.Int64Value(int64(item.RGID)),
RGName: types.StringValue(item.RGName),
ServiceAccount: &models.ServiceAccountInListModel{
GUID: types.StringValue(item.ServiceAccount.GUID),
Password: types.StringValue(item.ServiceAccount.Password),
Username: types.StringValue(item.ServiceAccount.Username),
},
Status: types.StringValue(item.Status),
TechStatus: types.StringValue(item.TechStatus),
UpdatedBy: types.StringValue(item.UpdatedBy),
UpdatedTime: types.Int64Value(int64(item.UpdatedTime)),
VINSID: types.Int64Value(int64(item.VINSID)),
WorkersGroup: flattenWG(ctx, &item.WorkersGroup),
}
temp.ACL, diags = types.ListValueFrom(ctx, types.StringType, item.ACL)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACL", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenItems")
return res
}
func flattenWG(ctx context.Context, WG *k8s.ListK8SGroups) []models.ItemWGInListModel {
tflog.Info(ctx, "Start flattenWG")
res := make([]models.ItemWGInListModel, 0, len(*WG))
var diags diag.Diagnostics
for _, k8sGroup := range *WG {
labels := make([]string, 0)
for _, label := range k8sGroup.Labels {
if strings.HasPrefix(label, "workersGroupName") {
continue
}
labels = append(labels, label)
}
temp := models.ItemWGInListModel{
CPU: types.Int64Value(int64(k8sGroup.CPU)),
DetailedInfo: flattenDetailedInfoList(ctx, &k8sGroup.DetailedInfo),
Disk: types.Int64Value(int64(k8sGroup.Disk)),
GUID: types.StringValue(k8sGroup.GUID),
WorkerGroupID: types.Int64Value(int64(k8sGroup.ID)),
WorkerGroupName: types.StringValue(k8sGroup.Name),
Num: types.Int64Value(int64(k8sGroup.Num)),
RAM: types.Int64Value(int64(k8sGroup.RAM)),
}
temp.Annotations, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Annotations)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenAnnotations", diags))
}
temp.Labels, diags = types.ListValueFrom(ctx, types.StringType, labels)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenLabels", diags))
}
temp.Taints, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Taints)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenTaints", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenWG")
return res
}
func flattenDetailedInfoList(ctx context.Context, di *k8s.ListDetailedInfo) []models.ItemDetailedInfoInListModel {
tflog.Info(ctx, "Start flattenDetailedInfoList")
res := make([]models.ItemDetailedInfoInListModel, 0, len(*di))
for _, info := range *di {
temp := models.ItemDetailedInfoInListModel{
Externalip: types.StringValue(info.Externalip),
ID: types.Int64Value(int64(info.ID)),
Name: types.StringValue(info.Name),
Status: types.StringValue(info.Status),
TechStatus: types.StringValue(info.TechStatus),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenDetailedInfoList")
return res
}

View File

@@ -0,0 +1,160 @@
package flattens
import (
"context"
"fmt"
"strings"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func DataSourceK8sListDeleted(ctx context.Context, state *models.K8SListDeletedModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8sListDeleted")
diags := diag.Diagnostics{}
k8sList, err := utilities.K8sListDeletedCheckPresence(ctx, state, c)
if err != nil {
diags.AddError("Error get k8s list info", err.Error())
return diags
}
id := uuid.New()
*state = models.K8SListDeletedModel{
ByID: state.ByID,
Name: state.Name,
IPAddress: state.IPAddress,
RGID: state.RGID,
LBID: state.LBID,
BasicServiceID: state.BasicServiceID,
TechStatus: state.TechStatus,
SortBy: state.SortBy,
Page: state.Page,
Size: state.Size,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
Items: flattenItemsDeleted(ctx, k8sList),
EntryCount: types.Int64Value(int64(k8sList.EntryCount)),
}
tflog.Info(ctx, "End FlattenDataSourceK8sListDeleted")
return nil
}
func flattenItemsDeleted(ctx context.Context, data *k8s.ListK8SClusters) []models.ItemInListDeletedK8SModel {
tflog.Info(ctx, "Start flattenItems")
var diags diag.Diagnostics
res := make([]models.ItemInListDeletedK8SModel, 0, len(data.Data))
for _, item := range data.Data {
temp := models.ItemInListDeletedK8SModel{
AccountID: types.Int64Value(int64(item.AccountID)),
AccountName: types.StringValue(item.AccountName),
BServiceID: types.Int64Value(int64(item.BServiceID)),
CIID: types.Int64Value(int64(item.CIID)),
CreatedBy: types.StringValue(item.CreatedBy),
CreatedTime: types.Int64Value(int64(item.CreatedTime)),
DeletedBy: types.StringValue(item.DeletedBy),
DeletedTime: types.Int64Value(int64(item.DeletedTime)),
Description: types.StringValue(item.Description),
ExtNetID: types.Int64Value(int64(item.ExtNetID)),
GID: types.Int64Value(int64(item.GID)),
GUID: types.Int64Value(int64(item.GUID)),
K8SID: types.Int64Value(int64(item.ID)),
LBID: types.Int64Value(int64(item.LBID)),
Milestones: types.Int64Value(int64(item.Milestones)),
Name: types.StringValue(item.Name),
NetworkPlugin: types.StringValue(item.NetworkPlugin),
RGID: types.Int64Value(int64(item.RGID)),
RGName: types.StringValue(item.RGName),
ServiceAccount: &models.ServiceAccountInListDeletedModel{
GUID: types.StringValue(item.ServiceAccount.GUID),
Password: types.StringValue(item.ServiceAccount.Password),
Username: types.StringValue(item.ServiceAccount.Username),
},
Status: types.StringValue(item.Status),
TechStatus: types.StringValue(item.TechStatus),
UpdatedBy: types.StringValue(item.UpdatedBy),
UpdatedTime: types.Int64Value(int64(item.UpdatedTime)),
VINSID: types.Int64Value(int64(item.VINSID)),
WorkersGroup: flattenWGDeleted(ctx, &item.WorkersGroup),
}
temp.ACL, diags = types.ListValueFrom(ctx, types.StringType, item.ACL)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACL", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenItems")
return res
}
func flattenWGDeleted(ctx context.Context, WG *k8s.ListK8SGroups) []models.ItemWGInListDeletedModel {
tflog.Info(ctx, "Start flattenWG")
res := make([]models.ItemWGInListDeletedModel, 0, len(*WG))
var diags diag.Diagnostics
for _, k8sGroup := range *WG {
labels := make([]string, 0)
for _, label := range k8sGroup.Labels {
if strings.HasPrefix(label, "workersGroupName") {
continue
}
labels = append(labels, label)
}
temp := models.ItemWGInListDeletedModel{
CPU: types.Int64Value(int64(k8sGroup.CPU)),
DetailedInfo: flattenDetailedInfoListDeleted(ctx, &k8sGroup.DetailedInfo),
Disk: types.Int64Value(int64(k8sGroup.Disk)),
GUID: types.StringValue(k8sGroup.GUID),
WorkerGroupID: types.Int64Value(int64(k8sGroup.ID)),
WorkerGroupName: types.StringValue(k8sGroup.Name),
Num: types.Int64Value(int64(k8sGroup.Num)),
RAM: types.Int64Value(int64(k8sGroup.RAM)),
}
temp.Annotations, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Annotations)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenAnnotations", diags))
}
temp.Labels, diags = types.ListValueFrom(ctx, types.StringType, labels)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenLabels", diags))
}
temp.Taints, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Taints)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenTaints", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenWG")
return res
}
func flattenDetailedInfoListDeleted(ctx context.Context, di *k8s.ListDetailedInfo) []models.ItemDetailedInfoInListDeletedModel {
tflog.Info(ctx, "Start flattenDetailedInfoList")
res := make([]models.ItemDetailedInfoInListDeletedModel, 0, len(*di))
for _, info := range *di {
temp := models.ItemDetailedInfoInListDeletedModel{
Externalip: types.StringValue(info.Externalip),
ID: types.Int64Value(int64(info.ID)),
Name: types.StringValue(info.Name),
Status: types.StringValue(info.Status),
TechStatus: types.StringValue(info.TechStatus),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenDetailedInfoList")
return res
}

View File

@@ -0,0 +1,128 @@
package flattens
import (
"context"
"fmt"
"strings"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func DataSourceK8sWg(ctx context.Context, state *models.K8SWgModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8sWg", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WorkerGroupID.ValueInt64()})
diags := diag.Diagnostics{}
k8SID := uint64(state.K8SID.ValueInt64())
wgID := uint64(state.WorkerGroupID.ValueInt64())
cluster, err := utilities.K8SCPResourceCheckPresence(ctx, k8SID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about cluster with ID %v", k8SID), err.Error())
return diags
}
curWg := k8s.ItemK8SGroup{}
for _, wg := range cluster.K8SGroups.Workers {
if wg.ID == wgID {
curWg = wg
break
}
}
if curWg.ID == 0 {
diags.AddError(fmt.Sprintf("WG with id %v in k8s cluster %v not found", wgID, k8SID), err.Error())
return diags
}
workersComputeList := make([]*compute.RecordCompute, 0, len(curWg.DetailedInfo))
for _, info := range curWg.DetailedInfo {
compute, err := utilities.ComputeCheckPresence(ctx, info.ID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about workerNode with ID %v", info.ID), err.Error())
return diags
}
workersComputeList = append(workersComputeList, compute)
}
id := uuid.New()
*state = models.K8SWgModel{
K8SID: state.K8SID,
Timeouts: state.Timeouts,
WorkerGroupID: state.WorkerGroupID,
Id: types.StringValue(id.String()),
CPU: types.Int64Value(int64(curWg.CPU)),
DetailedInfo: flattenDetailedInfoWg(ctx, &curWg.DetailedInfo, workersComputeList),
Disk: types.Int64Value(int64(curWg.Disk)),
GUID: types.StringValue(curWg.GUID),
WorkerGroupName: types.StringValue(curWg.Name),
Num: types.Int64Value(int64(curWg.Num)),
RAM: types.Int64Value(int64(curWg.RAM)),
}
labels := make([]string, 0)
for _, label := range curWg.Labels {
if strings.HasPrefix(label, "workersGroupName") {
continue
}
labels = append(labels, label)
}
state.Annotations, diags = types.ListValueFrom(ctx, types.StringType, curWg.Annotations)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenAnnotations", diags))
}
state.Labels, diags = types.ListValueFrom(ctx, types.StringType, labels)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenLabels", diags))
}
state.Taints, diags = types.ListValueFrom(ctx, types.StringType, curWg.Taints)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenTaints", diags))
}
tflog.Info(ctx, "End FlattenDataSourceK8sWg", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WorkerGroupID.ValueInt64()})
return nil
}
func flattenDetailedInfoWg(ctx context.Context, di *k8s.ListDetailedInfo, computes []*compute.RecordCompute) []models.ItemDetailedInfoInWgModel {
tflog.Info(ctx, "Start flattenDetailedInfoWg")
res := make([]models.ItemDetailedInfoInWgModel, 0, len(*di))
for i, detailedInfo := range *di {
temp := models.ItemDetailedInfoInWgModel{
ComputeId: types.Int64Value(int64(detailedInfo.ID)),
Name: types.StringValue(detailedInfo.Name),
Status: types.StringValue(detailedInfo.Status),
TechStatus: types.StringValue(detailedInfo.TechStatus),
Interfaces: flattenInterfacesWg(ctx, &computes[i].Interfaces),
NatableVinsIp: types.StringValue(computes[i].NatableVINSIP),
NatableVinsNetwork: types.StringValue(computes[i].NatableVINSNetwork),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenDetailedInfoWg")
return res
}
func flattenInterfacesWg(ctx context.Context, interfaces *compute.ListInterfaces) []models.ItemInterfacesInWgModel {
tflog.Info(ctx, "Start flattenInterfacesWg")
res := make([]models.ItemInterfacesInWgModel, 0, len(*interfaces))
for _, interfaceCompute := range *interfaces {
temp := models.ItemInterfacesInWgModel{
DefGw: types.StringValue(interfaceCompute.DefGW),
IpAddress: types.StringValue(interfaceCompute.IPAddress),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenInterfacesWg")
return res
}

View File

@@ -0,0 +1,38 @@
package flattens
import (
"context"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
)
func DataSourceK8sWgCloudInit(ctx context.Context, state *models.RecordK8SWgCloudInitDataSourceModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8sWgCloudInit", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WgId.ValueInt64()})
diags := diag.Diagnostics{}
metaData, err := c.CloudAPI().K8S().GetWorkerNodesMetaData(ctx, k8s.GetWorkerNodesMetaDataRequest{K8SID: uint64(state.K8SID.ValueInt64()), WorkersGroupID: uint64(state.WgId.ValueInt64())})
if err != nil {
diags.AddError("Cannot get info about wg cloud init with error: ", err.Error())
return diags
}
id := uuid.New()
*state = models.RecordK8SWgCloudInitDataSourceModel{
K8SID: state.K8SID,
WgId: state.WgId,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
CloudInit: types.StringValue(metaData),
}
tflog.Info(ctx, "End FlattenDataSourceK8sWgCloudInit", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "worker_group_id": state.WgId.ValueInt64()})
return nil
}

View File

@@ -0,0 +1,135 @@
package flattens
import (
"context"
"fmt"
"strings"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func DataSourceK8sWgList(ctx context.Context, state *models.K8SWgListModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceK8sWgList")
diags := diag.Diagnostics{}
k8SID := uint64(state.K8SID.ValueInt64())
cluster, err := utilities.K8SCPResourceCheckPresence(ctx, k8SID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about cluster with ID %d", k8SID), err.Error())
return diags
}
workersComputeList := make(map[uint64][]*compute.RecordCompute)
for _, worker := range cluster.K8SGroups.Workers {
workersComputeList[worker.ID] = make([]*compute.RecordCompute, 0, len(worker.DetailedInfo))
for _, info := range worker.DetailedInfo {
compute, err := utilities.ComputeCheckPresence(ctx, info.ID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about workerNode with ID %d", info.ID), err.Error())
return diags
}
workersComputeList[worker.ID] = append(workersComputeList[worker.ID], compute)
}
}
id := uuid.New()
*state = models.K8SWgListModel{
K8SID: state.K8SID,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
Items: flattenK8sWg(ctx, &cluster.K8SGroups.Workers, workersComputeList),
}
tflog.Info(ctx, "End FlattenDataSourceK8sWgList")
return nil
}
func flattenK8sWg(ctx context.Context, k8SGroupList *k8s.ListK8SGroups, workers map[uint64][]*compute.RecordCompute) []models.ItemWgListModel {
tflog.Info(ctx, "Start flattenK8sWg")
res := make([]models.ItemWgListModel, 0, len(*k8SGroupList))
var diags diag.Diagnostics
for _, k8sGroup := range *k8SGroupList {
labels := make([]string, 0)
for _, label := range k8sGroup.Labels {
if strings.HasPrefix(label, "workersGroupName") {
continue
}
labels = append(labels, label)
}
computes := workers[k8sGroup.ID]
temp := models.ItemWgListModel{
CPU: types.Int64Value(int64(k8sGroup.CPU)),
DetailedInfo: flattenDetailedInfoWgList(ctx, &k8sGroup.DetailedInfo, computes),
Disk: types.Int64Value(int64(k8sGroup.Disk)),
WorkerGroupID: types.Int64Value(int64(k8sGroup.ID)),
WorkerGroupName: types.StringValue(k8sGroup.Name),
Num: types.Int64Value(int64(k8sGroup.Num)),
RAM: types.Int64Value(int64(k8sGroup.RAM)),
}
temp.Annotations, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Annotations)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenAnnotations", diags))
}
temp.Labels, diags = types.ListValueFrom(ctx, types.StringType, labels)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenLabels", diags))
}
temp.Taints, diags = types.ListValueFrom(ctx, types.StringType, k8sGroup.Taints)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenTaints", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenK8sWg")
return res
}
func flattenDetailedInfoWgList(ctx context.Context, di *k8s.ListDetailedInfo, computes []*compute.RecordCompute) []models.ItemDetailedInfoDataSourceModel {
tflog.Info(ctx, "Start flattenDetailedInfoWgList")
res := make([]models.ItemDetailedInfoDataSourceModel, 0, len(*di))
for i, detailedInfo := range *di {
temp := models.ItemDetailedInfoDataSourceModel{
ComputeId: types.Int64Value(int64(detailedInfo.ID)),
Name: types.StringValue(detailedInfo.Name),
Status: types.StringValue(detailedInfo.Status),
TechStatus: types.StringValue(detailedInfo.TechStatus),
Interfaces: flattenInterfacesWgList(ctx, &computes[i].Interfaces),
NatableVinsIp: types.StringValue(computes[i].NatableVINSIP),
NatableVinsNetwork: types.StringValue(computes[i].NatableVINSNetwork),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenDetailedInfoWgList")
return res
}
func flattenInterfacesWgList(ctx context.Context, interfaces *compute.ListInterfaces) []models.ItemInterfacesDataSourceModel {
tflog.Info(ctx, "Start flattenInterfacesWgList")
res := make([]models.ItemInterfacesDataSourceModel, 0, len(*interfaces))
for _, interfaceCompute := range *interfaces {
temp := models.ItemInterfacesDataSourceModel{
DefGw: types.StringValue(interfaceCompute.DefGW),
IpAddress: types.StringValue(interfaceCompute.IPAddress),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenInterfacesWgList")
return res
}

View File

@@ -0,0 +1,231 @@
package flattens
import (
"context"
"fmt"
"strconv"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func K8SCPResource(ctx context.Context, plan *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenK8SCPResource", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
k8SID, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError("Cannot parsed ID cluster from state", err.Error())
return diags
}
cluster, err := utilities.K8SCPResourceCheckPresence(ctx, k8SID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about cluster with ID %d", k8SID), err.Error())
return diags
}
k8sList, err := utilities.K8sListForResourceCheckPresence(ctx, k8SID, c)
if err != nil || len(k8sList.Data) == 0 {
diags.AddError(fmt.Sprintf("Cluster with ID %v not found in List", k8SID), err.Error())
return diags
}
masterComputeList := make([]*compute.RecordCompute, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
for _, masterNode := range cluster.K8SGroups.Masters.DetailedInfo {
compute, err := utilities.ComputeCheckPresence(ctx, masterNode.ID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about masterNode with ID %d", masterNode.ID), err.Error())
return diags
}
masterComputeList = append(masterComputeList, compute)
}
*plan = models.ResourceK8SCPModel{
Name: types.StringValue(cluster.Name),
RGID: types.Int64Value(int64(cluster.RGID)),
K8SCIID: types.Int64Value(int64(cluster.CIID)),
NetworkPlugin: types.StringValue(cluster.NetworkPlugin),
SEPID: plan.SEPID,
SEPPool: plan.SEPPool,
WithLB: plan.WithLB,
HighlyAvailable: plan.HighlyAvailable,
AdditionalSANs: plan.AdditionalSANs,
InitConfiguration: plan.InitConfiguration,
ClusterConfiguration: plan.ClusterConfiguration,
KubeletConfiguration: plan.KubeletConfiguration,
KubeProxyConfiguration: plan.KubeProxyConfiguration,
JoinConfiguration: plan.JoinConfiguration,
Description: plan.Description,
ExtNetOnly: plan.ExtNetOnly,
OidcCertificate: plan.OidcCertificate,
Start: plan.Start,
Enabled: plan.Enabled,
Permanently: plan.Permanently,
Restore: plan.Restore,
Timeouts: plan.Timeouts,
LBSysctlParams: plan.LBSysctlParams,
Id: types.StringValue(strconv.Itoa(int(cluster.ID))),
LastUpdated: plan.LastUpdated,
DetailedInfo: flattenDetailedInfo(ctx, &cluster.K8SGroups.Masters.DetailedInfo, masterComputeList),
MasterGroupId: types.Int64Value(int64(cluster.K8SGroups.Masters.ID)),
MasterGroupName: types.StringValue(cluster.K8SGroups.Masters.Name),
Num: types.Int64Value(int64(cluster.K8SGroups.Masters.Num)),
CPU: types.Int64Value(int64(cluster.K8SGroups.Masters.CPU)),
RAM: types.Int64Value(int64(cluster.K8SGroups.Masters.RAM)),
Disk: types.Int64Value(int64(cluster.K8SGroups.Masters.Disk)),
ACL: flattenACL(ctx, &cluster.ACL),
AccountID: types.Int64Value(int64(cluster.AccountID)),
AccountName: types.StringValue(cluster.AccountName),
BServiceID: types.Int64Value(int64(cluster.BServiceID)),
CreatedBy: types.StringValue(cluster.CreatedBy),
CreatedTime: types.Int64Value(int64(cluster.CreatedTime)),
DeletedBy: types.StringValue(cluster.DeletedBy),
DeletedTime: types.Int64Value(int64(cluster.DeletedTime)),
K8SID: types.Int64Value(int64(cluster.ID)),
K8CIName: types.StringValue(cluster.K8CIName),
LBID: types.Int64Value(int64(cluster.LBID)),
RGName: types.StringValue(cluster.RGName),
Status: types.StringValue(cluster.Status),
TechStatus: types.StringValue(cluster.TechStatus),
UpdatedBy: types.StringValue(cluster.UpdatedBy),
UpdatedTime: types.Int64Value(int64(cluster.UpdatedTime)),
VinsId: types.Int64Value(int64(k8sList.Data[0].VINSID)),
}
if plan.AdditionalSANs.IsNull() {
plan.AdditionalSANs = types.ListNull(types.StringType)
}
if cluster.LBID != 0 {
lb, err := c.CloudAPI().LB().Get(ctx, lb.GetRequest{LBID: cluster.LBID})
if err != nil {
tflog.Error(ctx, fmt.Sprintf("Cannot get info about LB with ID %d", cluster.LBID)+err.Error())
}
plan.ExtNetID = types.Int64Value(int64(lb.ExtNetID))
plan.LBIP = types.StringValue(lb.PrimaryNode.FrontendIP)
} else {
plan.ExtNetID = types.Int64Value(0)
}
kubeconfig, err := c.CloudAPI().K8S().GetConfig(ctx, k8s.GetConfigRequest{K8SID: k8SID})
if err != nil {
tflog.Error(ctx, "Could not get kubeconfig:"+err.Error())
}
plan.Kubeconfig = types.StringValue(kubeconfig)
tflog.Info(ctx, "End FlattenK8SCPResource", map[string]any{"k8s_id": plan.K8SID.ValueInt64()})
return nil
}
func flattenDetailedInfo(ctx context.Context, di *k8s.ListDetailedInfo, computes []*compute.RecordCompute) types.List {
tflog.Info(ctx, "Start flattenDetailedInfo")
tempSlice := make([]types.Object, 0, len(*di))
for i, detailedInfo := range *di {
temp := models.ItemDetailedInfoModel{
ComputeId: types.Int64Value(int64(detailedInfo.ID)),
Name: types.StringValue(detailedInfo.Name),
Status: types.StringValue(detailedInfo.Status),
TechStatus: types.StringValue(detailedInfo.TechStatus),
Interfaces: flattenInterfaces(ctx, &computes[i].Interfaces),
NatableVinsIp: types.StringValue(computes[i].NatableVINSIP),
NatableVinsNetwork: types.StringValue(computes[i].NatableVINSNetwork),
}
obj, err := types.ObjectValueFrom(ctx, models.ItemDetailedInfo, temp)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDetailedInfo struct to obj", err))
}
tempSlice = append(tempSlice, obj)
}
res, err := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemDetailedInfo}, tempSlice)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDetailedInfo", err))
}
tflog.Info(ctx, "End flattenDetailedInfo")
return res
}
func flattenInterfaces(ctx context.Context, interfaces *compute.ListInterfaces) types.List {
tflog.Info(ctx, "Start flattenInterfaces")
tempSlice := make([]types.Object, 0, len(*interfaces))
for _, interfaceCompute := range *interfaces {
temp := models.ItemInterfacesModel{
DefGw: types.StringValue(interfaceCompute.DefGW),
IpAddress: types.StringValue(interfaceCompute.IPAddress),
}
obj, err := types.ObjectValueFrom(ctx, models.ItemInterfaces, temp)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenInterfaces struct to obj", err))
}
tempSlice = append(tempSlice, obj)
}
res, err := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemInterfaces}, tempSlice)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenInterfaces", err))
}
tflog.Info(ctx, "End flattenInterfaces")
return res
}
func flattenACL(ctx context.Context, acl *k8s.RecordACL) types.Object {
tflog.Info(ctx, "Start flattenACL")
temp := models.RecordACLModel{
AccountACL: flattenACLItems(ctx, &acl.AccountACL),
K8SACL: flattenACLItems(ctx, &acl.K8SACL),
RGACL: flattenACLItems(ctx, &acl.RGACL),
}
res, err := types.ObjectValueFrom(ctx, models.ListACL, temp)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACL struct to obj", err))
}
tflog.Info(ctx, "End flattenACL")
return res
}
func flattenACLItems(ctx context.Context, item *k8s.ListACL) types.List {
tflog.Info(ctx, "Start flattenACLItems")
tempSlice := make([]types.Object, 0, len(*item))
for _, aclItem := range *item {
temp := models.ItemACLModel{
Explicit: types.BoolValue(aclItem.Explicit),
GUID: types.StringValue(aclItem.GUID),
Right: types.StringValue(aclItem.Right),
Status: types.StringValue(aclItem.Status),
Type: types.StringValue(aclItem.Type),
UserGroupID: types.StringValue(aclItem.UserGroupID),
}
obj, err := types.ObjectValueFrom(ctx, models.ItemAcl, temp)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACLItems struct to obj", err))
}
tempSlice = append(tempSlice, obj)
}
res, err := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemAcl}, tempSlice)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACLItems", err))
}
tflog.Info(ctx, "End flattenACLItems")
return res
}

View File

@@ -0,0 +1,138 @@
package flattens
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
func K8SWGResource(ctx context.Context, plan *models.ResourceK8SWGModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenK8SWGResource", map[string]any{"wg_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
wg, k8sId, err := utilities.K8SWGResourceCheckPresence(ctx, plan, c)
if err != nil {
diags.AddError("Cannot get info about wg ", err.Error())
return diags
}
workersComputeList := make([]*compute.RecordCompute, 0, len(wg.DetailedInfo))
for _, info := range wg.DetailedInfo {
compute, err := utilities.ComputeCheckPresence(ctx, info.ID, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about workerNode with ID %d", info.ID), err.Error())
return diags
}
workersComputeList = append(workersComputeList, compute)
}
*plan = models.ResourceK8SWGModel{
K8SID: types.Int64Value(int64(k8sId)),
Name: types.StringValue(wg.Name),
Num: types.Int64Value(int64(wg.Num)),
CPU: types.Int64Value(int64(wg.CPU)),
RAM: types.Int64Value(int64(wg.RAM)),
Disk: types.Int64Value(int64(wg.Disk)),
WorkerSEPID: plan.WorkerSEPID,
WorkerSEPPool: plan.WorkerSEPPool,
CloudInit: plan.CloudInit,
Timeouts: plan.Timeouts,
Id: types.StringValue(strconv.Itoa(int(wg.ID))),
WorkerGroupId: types.Int64Value(int64(wg.ID)),
LastUpdated: plan.LastUpdated,
DetailedInfo: flattenDetailedInfoInK8sWG(ctx, &wg.DetailedInfo, workersComputeList),
GUID: types.StringValue(wg.GUID),
}
labels := make([]string, 0)
for _, label := range wg.Labels {
if strings.HasPrefix(label, "workersGroupName") {
continue
}
labels = append(labels, label)
}
plan.Annotations, diags = types.ListValueFrom(ctx, types.StringType, wg.Annotations)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenAnnotations", diags))
}
plan.Labels, diags = types.ListValueFrom(ctx, types.StringType, labels)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenLabels", diags))
}
plan.Taints, diags = types.ListValueFrom(ctx, types.StringType, wg.Taints)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenTaints", diags))
}
tflog.Info(ctx, "End FlattenK8SWGResource", map[string]any{"wg_id": plan.Id.ValueString()})
return nil
}
func flattenDetailedInfoInK8sWG(ctx context.Context, di *k8s.ListDetailedInfo, computes []*compute.RecordCompute) types.List {
tflog.Info(ctx, "Start flattenDetailedInfoInK8sWG")
tempSlice := make([]types.Object, 0, len(*di))
for i, detailedInfo := range *di {
temp := models.ItemDetailedInfoModel{
ComputeId: types.Int64Value(int64(detailedInfo.ID)),
Name: types.StringValue(detailedInfo.Name),
Status: types.StringValue(detailedInfo.Status),
TechStatus: types.StringValue(detailedInfo.TechStatus),
Interfaces: flattenInterfacesInK8sWG(ctx, &computes[i].Interfaces),
NatableVinsIp: types.StringValue(computes[i].NatableVINSIP),
NatableVinsNetwork: types.StringValue(computes[i].NatableVINSNetwork),
}
obj, err := types.ObjectValueFrom(ctx, models.ItemDetailedInfo, temp)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDetailedInfoInK8sWG struct to obj", err))
}
tempSlice = append(tempSlice, obj)
}
res, err := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemDetailedInfo}, tempSlice)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDetailedInfoInK8sWG", err))
}
tflog.Info(ctx, "End flattenDetailedInfoInK8sWG")
return res
}
func flattenInterfacesInK8sWG(ctx context.Context, interfaces *compute.ListInterfaces) types.List {
tflog.Info(ctx, "Start flattenInterfacesInK8sWG")
tempSlice := make([]types.Object, 0, len(*interfaces))
for _, interfaceCompute := range *interfaces {
temp := models.ItemInterfacesModel{
DefGw: types.StringValue(interfaceCompute.DefGW),
IpAddress: types.StringValue(interfaceCompute.IPAddress),
}
obj, err := types.ObjectValueFrom(ctx, models.ItemInterfaces, temp)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenInterfacesInK8sWG struct to obj", err))
}
tempSlice = append(tempSlice, obj)
}
res, err := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemInterfaces}, tempSlice)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenInterfacesInK8sWG", err))
}
tflog.Info(ctx, "End flattenInterfacesInK8sWG")
return res
}

View File

@@ -0,0 +1,36 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type K8ciListModel struct {
// request fields
ByID types.Int64 `tfsdk:"by_id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
WorkerDriver types.String `tfsdk:"worker_driver"`
MasterDriver types.String `tfsdk:"master_driver"`
NetworkPlugins types.String `tfsdk:"network_plugins"`
IncludeDisabled types.Bool `tfsdk:"include_disabled"`
Page types.Int64 `tfsdk:"page"`
SortBy types.String `tfsdk:"sort_by"`
Size types.Int64 `tfsdk:"size"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
Items []ItemInListK8ciModel `tfsdk:"items"`
EntryCount types.Int64 `tfsdk:"entry_count"`
}
type ItemInListK8ciModel struct {
CreatedTime types.Int64 `tfsdk:"created_time"`
Description types.String `tfsdk:"desc"`
K8CIID types.Int64 `tfsdk:"k8ci_id"`
LBImageID types.Int64 `tfsdk:"lb_image_id"`
K8CIName types.String `tfsdk:"k8ci_name"`
NetworkPlugins types.List `tfsdk:"network_plugins"`
Status types.String `tfsdk:"status"`
Version types.String `tfsdk:"version"`
}

View File

@@ -0,0 +1,93 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type RecordK8SDataSourceModel struct {
// request fields
K8SID types.Int64 `tfsdk:"k8s_id"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
ACL *RecordACLDataSourceModel `tfsdk:"acl"`
AccountID types.Int64 `tfsdk:"account_id"`
AccountName types.String `tfsdk:"account_name"`
BServiceID types.Int64 `tfsdk:"bservice_id"`
K8CI types.Int64 `tfsdk:"k8sci_id"`
CreatedBy types.String `tfsdk:"created_by"`
CreatedTime types.Int64 `tfsdk:"created_time"`
DeletedBy types.String `tfsdk:"deleted_by"`
DeletedTime types.Int64 `tfsdk:"deleted_time"`
ExtNetID types.Int64 `tfsdk:"extnet_id"`
K8CIName types.String `tfsdk:"k8sci_name"`
Masters *MasterGroupDataSourceModel `tfsdk:"masters"`
Workers []ItemK8SGroupDataSourceModel `tfsdk:"workers"`
LBID types.Int64 `tfsdk:"lb_id"`
LBIP types.String `tfsdk:"lb_ip"`
Name types.String `tfsdk:"name"`
NetworkPlugin types.String `tfsdk:"network_plugin"`
RGID types.Int64 `tfsdk:"rg_id"`
RGName types.String `tfsdk:"rg_name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
UpdatedBy types.String `tfsdk:"updated_by"`
UpdatedTime types.Int64 `tfsdk:"updated_time"`
Kubeconfig types.String `tfsdk:"kubeconfig"`
VinsId types.Int64 `tfsdk:"vins_id"`
}
type RecordACLDataSourceModel struct {
AccountACL []ItemACLDataSourceModel `tfsdk:"account_acl"`
K8SACL []ItemACLDataSourceModel `tfsdk:"k8s_acl"`
RGACL []ItemACLDataSourceModel `tfsdk:"rg_acl"`
}
type ItemACLDataSourceModel struct {
Explicit types.Bool `tfsdk:"explicit"`
GUID types.String `tfsdk:"guid"`
Right types.String `tfsdk:"right"`
Status types.String `tfsdk:"status"`
Type types.String `tfsdk:"type"`
UserGroupID types.String `tfsdk:"user_group_id"`
}
type MasterGroupDataSourceModel struct {
CPU types.Int64 `tfsdk:"cpu"`
DetailedInfo []ItemDetailedInfoDataSourceModel `tfsdk:"detailed_info"`
Disk types.Int64 `tfsdk:"disk"`
MasterGroupId types.Int64 `tfsdk:"master_group_id"`
MasterGroupName types.String `tfsdk:"master_group_name"`
Num types.Int64 `tfsdk:"num"`
RAM types.Int64 `tfsdk:"ram"`
}
type ItemK8SGroupDataSourceModel struct {
Annotations types.List `tfsdk:"annotations"`
CPU types.Int64 `tfsdk:"cpu"`
DetailedInfo []ItemDetailedInfoDataSourceModel `tfsdk:"detailed_info"`
Disk types.Int64 `tfsdk:"disk"`
GUID types.String `tfsdk:"guid"`
WorkerGroupID types.Int64 `tfsdk:"worker_group_id"`
Labels types.List `tfsdk:"labels"`
WorkerGroupName types.String `tfsdk:"worker_group_name"`
Num types.Int64 `tfsdk:"num"`
RAM types.Int64 `tfsdk:"ram"`
Taints types.List `tfsdk:"taints"`
}
type ItemDetailedInfoDataSourceModel struct {
ComputeId types.Int64 `tfsdk:"compute_id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Interfaces []ItemInterfacesDataSourceModel `tfsdk:"interfaces"`
NatableVinsIp types.String `tfsdk:"natable_vins_ip"`
NatableVinsNetwork types.String `tfsdk:"natable_vins_network"`
}
type ItemInterfacesDataSourceModel struct {
DefGw types.String `tfsdk:"def_gw"`
IpAddress types.String `tfsdk:"ip_address"`
}

View File

@@ -0,0 +1,24 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type K8SComputesModel struct {
// request fields
K8SID types.Int64 `tfsdk:"k8s_id"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
Masters []ItemComputeModel `tfsdk:"masters"`
Workers []ItemComputeModel `tfsdk:"workers"`
}
type ItemComputeModel struct {
ComputeId types.Int64 `tfsdk:"compute_id"`
Name types.String `tfsdk:"name"`
GroupName types.String `tfsdk:"group_name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
}

View File

@@ -0,0 +1,85 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type K8SListModel struct {
// request fields
ByID types.Int64 `tfsdk:"by_id"`
Name types.String `tfsdk:"name"`
IPAddress types.String `tfsdk:"ip_address"`
RGID types.Int64 `tfsdk:"rg_id"`
LBID types.Int64 `tfsdk:"lb_id"`
BasicServiceID types.Int64 `tfsdk:"bservice_id"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
IncludeDeleted types.Bool `tfsdk:"includedeleted"`
SortBy types.String `tfsdk:"sort_by"`
Page types.Int64 `tfsdk:"page"`
Size types.Int64 `tfsdk:"size"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
Items []ItemInListK8SModel `tfsdk:"items"`
EntryCount types.Int64 `tfsdk:"entry_count"`
}
type ItemInListK8SModel struct {
AccountID types.Int64 `tfsdk:"account_id"`
AccountName types.String `tfsdk:"account_name"`
ACL types.List `tfsdk:"acl"`
BServiceID types.Int64 `tfsdk:"bservice_id"`
CIID types.Int64 `tfsdk:"k8sci_id"`
CreatedBy types.String `tfsdk:"created_by"`
CreatedTime types.Int64 `tfsdk:"created_time"`
DeletedBy types.String `tfsdk:"deleted_by"`
DeletedTime types.Int64 `tfsdk:"deleted_time"`
Description types.String `tfsdk:"desc"`
ExtNetID types.Int64 `tfsdk:"extnet_id"`
GID types.Int64 `tfsdk:"gid"`
GUID types.Int64 `tfsdk:"guid"`
K8SID types.Int64 `tfsdk:"k8s_id"`
LBID types.Int64 `tfsdk:"lb_id"`
Milestones types.Int64 `tfsdk:"milestones"`
Name types.String `tfsdk:"k8s_name"`
NetworkPlugin types.String `tfsdk:"network_plugin"`
RGID types.Int64 `tfsdk:"rg_id"`
RGName types.String `tfsdk:"rg_name"`
ServiceAccount *ServiceAccountInListModel `tfsdk:"service_account"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
UpdatedBy types.String `tfsdk:"updated_by"`
UpdatedTime types.Int64 `tfsdk:"updated_time"`
VINSID types.Int64 `tfsdk:"vins_id"`
WorkersGroup []ItemWGInListModel `tfsdk:"workers_groups"`
}
type ServiceAccountInListModel struct {
GUID types.String `tfsdk:"guid"`
Password types.String `tfsdk:"password"`
Username types.String `tfsdk:"username"`
}
type ItemWGInListModel struct {
Annotations types.List `tfsdk:"annotations"`
CPU types.Int64 `tfsdk:"cpu"`
DetailedInfo []ItemDetailedInfoInListModel `tfsdk:"detailed_info"`
Disk types.Int64 `tfsdk:"disk"`
GUID types.String `tfsdk:"guid"`
WorkerGroupID types.Int64 `tfsdk:"worker_group_id"`
Labels types.List `tfsdk:"labels"`
WorkerGroupName types.String `tfsdk:"worker_group_name"`
Num types.Int64 `tfsdk:"num"`
RAM types.Int64 `tfsdk:"ram"`
Taints types.List `tfsdk:"taints"`
}
type ItemDetailedInfoInListModel struct {
Externalip types.String `tfsdk:"externalip"`
ID types.Int64 `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
}

View File

@@ -0,0 +1,83 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type K8SListDeletedModel struct {
// request fields
ByID types.Int64 `tfsdk:"by_id"`
Name types.String `tfsdk:"name"`
IPAddress types.String `tfsdk:"ip_address"`
RGID types.Int64 `tfsdk:"rg_id"`
LBID types.Int64 `tfsdk:"lb_id"`
BasicServiceID types.Int64 `tfsdk:"bservice_id"`
TechStatus types.String `tfsdk:"tech_status"`
SortBy types.String `tfsdk:"sort_by"`
Page types.Int64 `tfsdk:"page"`
Size types.Int64 `tfsdk:"size"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
Items []ItemInListDeletedK8SModel `tfsdk:"items"`
EntryCount types.Int64 `tfsdk:"entry_count"`
}
type ItemInListDeletedK8SModel struct {
AccountID types.Int64 `tfsdk:"account_id"`
AccountName types.String `tfsdk:"account_name"`
ACL types.List `tfsdk:"acl"`
BServiceID types.Int64 `tfsdk:"bservice_id"`
CIID types.Int64 `tfsdk:"k8sci_id"`
CreatedBy types.String `tfsdk:"created_by"`
CreatedTime types.Int64 `tfsdk:"created_time"`
DeletedBy types.String `tfsdk:"deleted_by"`
DeletedTime types.Int64 `tfsdk:"deleted_time"`
Description types.String `tfsdk:"desc"`
ExtNetID types.Int64 `tfsdk:"extnet_id"`
GID types.Int64 `tfsdk:"gid"`
GUID types.Int64 `tfsdk:"guid"`
K8SID types.Int64 `tfsdk:"k8s_id"`
LBID types.Int64 `tfsdk:"lb_id"`
Milestones types.Int64 `tfsdk:"milestones"`
Name types.String `tfsdk:"k8s_name"`
NetworkPlugin types.String `tfsdk:"network_plugin"`
RGID types.Int64 `tfsdk:"rg_id"`
RGName types.String `tfsdk:"rg_name"`
ServiceAccount *ServiceAccountInListDeletedModel `tfsdk:"service_account"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
UpdatedBy types.String `tfsdk:"updated_by"`
UpdatedTime types.Int64 `tfsdk:"updated_time"`
VINSID types.Int64 `tfsdk:"vins_id"`
WorkersGroup []ItemWGInListDeletedModel `tfsdk:"workers_groups"`
}
type ServiceAccountInListDeletedModel struct {
GUID types.String `tfsdk:"guid"`
Password types.String `tfsdk:"password"`
Username types.String `tfsdk:"username"`
}
type ItemWGInListDeletedModel struct {
Annotations types.List `tfsdk:"annotations"`
CPU types.Int64 `tfsdk:"cpu"`
DetailedInfo []ItemDetailedInfoInListDeletedModel `tfsdk:"detailed_info"`
Disk types.Int64 `tfsdk:"disk"`
GUID types.String `tfsdk:"guid"`
WorkerGroupID types.Int64 `tfsdk:"worker_group_id"`
Labels types.List `tfsdk:"labels"`
WorkerGroupName types.String `tfsdk:"worker_group_name"`
Num types.Int64 `tfsdk:"num"`
RAM types.Int64 `tfsdk:"ram"`
Taints types.List `tfsdk:"taints"`
}
type ItemDetailedInfoInListDeletedModel struct {
Externalip types.String `tfsdk:"externalip"`
ID types.Int64 `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
}

View File

@@ -0,0 +1,40 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type K8SWgModel struct {
// request fields
K8SID types.Int64 `tfsdk:"k8s_id"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
WorkerGroupID types.Int64 `tfsdk:"wg_id"`
// response fields
Id types.String `tfsdk:"id"`
Annotations types.List `tfsdk:"annotations"`
CPU types.Int64 `tfsdk:"cpu"`
DetailedInfo []ItemDetailedInfoInWgModel `tfsdk:"detailed_info"`
Disk types.Int64 `tfsdk:"disk"`
GUID types.String `tfsdk:"guid"`
Labels types.List `tfsdk:"labels"`
WorkerGroupName types.String `tfsdk:"worker_group_name"`
Num types.Int64 `tfsdk:"num"`
RAM types.Int64 `tfsdk:"ram"`
Taints types.List `tfsdk:"taints"`
}
type ItemDetailedInfoInWgModel struct {
ComputeId types.Int64 `tfsdk:"compute_id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Interfaces []ItemInterfacesInWgModel `tfsdk:"interfaces"`
NatableVinsIp types.String `tfsdk:"natable_vins_ip"`
NatableVinsNetwork types.String `tfsdk:"natable_vins_network"`
}
type ItemInterfacesInWgModel struct {
DefGw types.String `tfsdk:"def_gw"`
IpAddress types.String `tfsdk:"ip_address"`
}

View File

@@ -0,0 +1,16 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type RecordK8SWgCloudInitDataSourceModel struct {
// request fields
K8SID types.Int64 `tfsdk:"k8s_id"`
WgId types.Int64 `tfsdk:"wg_id"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
CloudInit types.String `tfsdk:"cloud_init"`
}

View File

@@ -0,0 +1,45 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type K8SWgListModel struct {
// request fields
K8SID types.Int64 `tfsdk:"k8s_id"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
Items []ItemWgListModel `tfsdk:"items"`
}
type ItemWgListModel struct {
Annotations types.List `tfsdk:"annotations"`
CPU types.Int64 `tfsdk:"cpu"`
DetailedInfo []ItemDetailedInfoDataSourceModel `tfsdk:"detailed_info"`
Disk types.Int64 `tfsdk:"disk"`
GUID types.String `tfsdk:"guid"`
Labels types.List `tfsdk:"labels"`
WorkerGroupID types.Int64 `tfsdk:"worker_group_id"`
WorkerGroupName types.String `tfsdk:"worker_group_name"`
Num types.Int64 `tfsdk:"num"`
RAM types.Int64 `tfsdk:"ram"`
Taints types.List `tfsdk:"taints"`
}
type ItemDetailedInfoInWgListModel struct {
ComputeId types.Int64 `tfsdk:"compute_id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Interfaces []ItemInterfacesInWgModel `tfsdk:"interfaces"`
NatableVinsIp types.String `tfsdk:"natable_vins_ip"`
NatableVinsNetwork types.String `tfsdk:"natable_vins_network"`
}
type ItemInterfacesInWgListModel struct {
DefGw types.String `tfsdk:"def_gw"`
IpAddress types.String `tfsdk:"ip_address"`
}

View File

@@ -0,0 +1,124 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type ResourceK8SCPModel struct {
// request fields
Name types.String `tfsdk:"name"`
RGID types.Int64 `tfsdk:"rg_id"`
K8SCIID types.Int64 `tfsdk:"k8sci_id"`
NetworkPlugin types.String `tfsdk:"network_plugin"`
SEPID types.Int64 `tfsdk:"sep_id"`
SEPPool types.String `tfsdk:"sep_pool"`
Num types.Int64 `tfsdk:"num"`
CPU types.Int64 `tfsdk:"cpu"`
RAM types.Int64 `tfsdk:"ram"`
Disk types.Int64 `tfsdk:"disk"`
ExtNetID types.Int64 `tfsdk:"extnet_id"`
VinsId types.Int64 `tfsdk:"vins_id"`
WithLB types.Bool `tfsdk:"with_lb"`
HighlyAvailable types.Bool `tfsdk:"ha_mode"`
AdditionalSANs types.List `tfsdk:"additional_sans"`
InitConfiguration types.String `tfsdk:"init_config"`
ClusterConfiguration types.String `tfsdk:"cluster_config"`
KubeletConfiguration types.String `tfsdk:"kubelet_config"`
KubeProxyConfiguration types.String `tfsdk:"kube_proxy_config"`
JoinConfiguration types.String `tfsdk:"join_config"`
Description types.String `tfsdk:"desc"`
ExtNetOnly types.Bool `tfsdk:"extnet_only"`
OidcCertificate types.String `tfsdk:"oidc_cert"`
Start types.Bool `tfsdk:"start"`
Enabled types.Bool `tfsdk:"enabled"`
Permanently types.Bool `tfsdk:"permanently"`
Restore types.Bool `tfsdk:"restore"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
LBSysctlParams types.List `tfsdk:"lb_sysctl_params"`
// response fields
Id types.String `tfsdk:"id"`
LastUpdated types.String `tfsdk:"last_updated"`
ACL types.Object `tfsdk:"acl"`
DetailedInfo types.List `tfsdk:"detailed_info"`
AccountID types.Int64 `tfsdk:"account_id"`
AccountName types.String `tfsdk:"account_name"`
BServiceID types.Int64 `tfsdk:"bservice_id"`
CreatedBy types.String `tfsdk:"created_by"`
CreatedTime types.Int64 `tfsdk:"created_time"`
DeletedBy types.String `tfsdk:"deleted_by"`
DeletedTime types.Int64 `tfsdk:"deleted_time"`
K8SID types.Int64 `tfsdk:"k8s_id"`
K8CIName types.String `tfsdk:"k8s_ci_name"`
LBID types.Int64 `tfsdk:"lb_id"`
LBIP types.String `tfsdk:"lb_ip"`
MasterGroupId types.Int64 `tfsdk:"master_group_id"`
MasterGroupName types.String `tfsdk:"master_group_name"`
RGName types.String `tfsdk:"rg_name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
UpdatedBy types.String `tfsdk:"updated_by"`
UpdatedTime types.Int64 `tfsdk:"updated_time"`
Kubeconfig types.String `tfsdk:"kubeconfig"`
}
type RecordACLModel struct {
AccountACL types.List `tfsdk:"account_acl"`
K8SACL types.List `tfsdk:"k8s_acl"`
RGACL types.List `tfsdk:"rg_acl"`
}
type ItemACLModel struct {
Explicit types.Bool `tfsdk:"explicit"`
GUID types.String `tfsdk:"guid"`
Right types.String `tfsdk:"right"`
Status types.String `tfsdk:"status"`
Type types.String `tfsdk:"type"`
UserGroupID types.String `tfsdk:"user_group_id"`
}
type ItemDetailedInfoModel struct {
ComputeId types.Int64 `tfsdk:"compute_id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Interfaces types.List `tfsdk:"interfaces"`
NatableVinsIp types.String `tfsdk:"natable_vins_ip"`
NatableVinsNetwork types.String `tfsdk:"natable_vins_network"`
}
type ItemInterfacesModel struct {
DefGw types.String `tfsdk:"def_gw"`
IpAddress types.String `tfsdk:"ip_address"`
}
var ItemInterfaces map[string]attr.Type = map[string]attr.Type{
"def_gw": types.StringType,
"ip_address": types.StringType,
}
var ListACL map[string]attr.Type = map[string]attr.Type{
"account_acl": types.ListType{ElemType: types.ObjectType{AttrTypes: ItemAcl}},
"k8s_acl": types.ListType{ElemType: types.ObjectType{AttrTypes: ItemAcl}},
"rg_acl": types.ListType{ElemType: types.ObjectType{AttrTypes: ItemAcl}},
}
var ItemAcl map[string]attr.Type = map[string]attr.Type{
"explicit": types.BoolType,
"guid": types.StringType,
"right": types.StringType,
"status": types.StringType,
"type": types.StringType,
"user_group_id": types.StringType,
}
var ItemDetailedInfo map[string]attr.Type = map[string]attr.Type{
"compute_id": types.Int64Type,
"name": types.StringType,
"status": types.StringType,
"tech_status": types.StringType,
"interfaces": types.ListType{ElemType: types.ObjectType{AttrTypes: ItemInterfaces}},
"natable_vins_ip": types.StringType,
"natable_vins_network": types.StringType,
}

View File

@@ -0,0 +1,60 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type ResourceK8SWGModel struct {
// request fields
K8SID types.Int64 `tfsdk:"k8s_id"`
Name types.String `tfsdk:"name"`
Num types.Int64 `tfsdk:"num"`
CPU types.Int64 `tfsdk:"cpu"`
RAM types.Int64 `tfsdk:"ram"`
Disk types.Int64 `tfsdk:"disk"`
Annotations types.List `tfsdk:"annotations"`
Labels types.List `tfsdk:"labels"`
Taints types.List `tfsdk:"taints"`
WorkerSEPID types.Int64 `tfsdk:"worker_sep_id"`
WorkerSEPPool types.String `tfsdk:"worker_sep_pool"`
CloudInit types.String `tfsdk:"cloud_init"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// response fields
Id types.String `tfsdk:"id"`
LastUpdated types.String `tfsdk:"last_updated"`
WorkerGroupId types.Int64 `tfsdk:"wg_id"`
DetailedInfo types.List `tfsdk:"detailed_info"`
GUID types.String `tfsdk:"guid"`
}
type ItemDetailedInfoInK8sWGModel struct {
ComputeId types.Int64 `tfsdk:"compute_id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Interfaces types.List `tfsdk:"interfaces"`
NatableVinsIp types.String `tfsdk:"natable_vins_ip"`
NatableVinsNetwork types.String `tfsdk:"natable_vins_network"`
}
type ItemInterfacesInK8sWGModel struct {
DefGw types.String `tfsdk:"def_gw"`
IpAddress types.String `tfsdk:"ip_address"`
}
var ItemInterfacesInK8sWG map[string]attr.Type = map[string]attr.Type{
"def_gw": types.StringType,
"ip_address": types.StringType,
}
var ItemDetailedInfoInK8sWG map[string]attr.Type = map[string]attr.Type{
"compute_id": types.Int64Type,
"name": types.StringType,
"status": types.StringType,
"tech_status": types.StringType,
"interfaces": types.ListType{ElemType: types.ObjectType{AttrTypes: ItemInterfaces}},
"natable_vins_ip": types.StringType,
"natable_vins_network": types.StringType,
}

View File

@@ -0,0 +1,319 @@
package k8s
import (
"context"
"time"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &resourceK8SCP{}
_ resource.ResourceWithImportState = &resourceK8SCP{}
)
// NewResourceK8S_CP is a helper function to simplify the provider implementation.
func NewResourceK8SCP() resource.Resource {
return &resourceK8SCP{}
}
// resourceK8S_CP is the resource implementation.
type resourceK8SCP struct {
client *decort.DecortClient
}
// Create the resource and sets the initial Terraform state.
func (r *resourceK8SCP) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan models.ResourceK8SCPModel
// Get plan for create cluster
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
tflog.Info(ctx, "Start create k8s_cp cluster", map[string]any{"name": plan.Name.ValueString()})
// Set timeouts
createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout30m)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
// Сhecking for values in the platform
resp.Diagnostics.Append(utilities.CheckParamsExistenceCP(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error check input values")
return
}
// Make request and get response
task, err := r.client.CloudAPI().K8S().Create(ctx, utilities.CreateRequestResourceK8CP(ctx, &plan))
if err != nil {
tflog.Error(ctx, "Error response for create k8s_cp cluster")
resp.Diagnostics.AddError("Unable to Create K8SCP", err.Error())
return
}
// Check cluster and validated
resp.Diagnostics.Append(utilities.CheckResourceK8SCPCreateAndDeleteWG(ctx, &plan, r.client, task)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error create k8s_cp cluster")
return
}
// Map response body to schema
resp.Diagnostics.Append(flattens.K8SCPResource(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s_cp cluster")
return
}
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End create k8s_cp cluster", map[string]any{"k8s_id": plan.K8SID.ValueInt64()})
}
// Read refreshes the Terraform state with the latest data.
func (r *resourceK8SCP) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state models.ResourceK8SCPModel
// Get current state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start read k8s_cp cluster", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout600s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Read status cluster and if it is necessary to restore it
resp.Diagnostics.Append(utilities.K8SCPReadStatus(ctx, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read status or restore")
return
}
// Overwrite items with refreshed state
resp.Diagnostics.Append(flattens.K8SCPResource(ctx, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s_cp cluster")
return
}
// Set refreshed state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End read k8s_cp cluster", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceK8SCP) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan models.ResourceK8SCPModel
var state models.ResourceK8SCPModel
// Retrieve values from plan
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
// Retrieve values from state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the state")
return
}
tflog.Info(ctx, "Start update k8s_cp cluster", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
// Set timeouts
updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout600s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, updateTimeout)
defer cancel()
// Сhecking for values in the platform
resp.Diagnostics.Append(utilities.CheckParamsExistenceCP(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error check input values")
return
}
// Update Name or/and Description cluster
if !plan.Name.Equal(state.Name) || !plan.Description.Equal(state.Description) {
resp.Diagnostics.Append(utilities.K8SCPUpdateNameOrDescription(ctx, &plan, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error update info")
return
}
}
// Update Enable/Disable cluster
if !plan.Enabled.Equal(state.Enabled) {
resp.Diagnostics.Append(utilities.K8SCPEnableDisable(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error Enable/Disable")
return
}
}
// Update Start/Stop cluster
if !plan.Start.Equal(state.Start) {
resp.Diagnostics.Append(utilities.K8SCPStartStop(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error Start/Stop")
return
}
}
// Delete master node from cluster
if (plan.Num.ValueInt64() < state.Num.ValueInt64()) && (plan.Num.ValueInt64() != 0) {
resp.Diagnostics.Append(utilities.K8SCPDeleteMaster(ctx, &plan, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error Delete master node")
return
}
}
//Update LB params
if (state.WithLB.IsNull() || state.WithLB.ValueBool()) && !plan.LBSysctlParams.Equal(state.LBSysctlParams) {
resp.Diagnostics.Append(utilities.K8CPUpdateSysctlParams(ctx, &plan, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error Update LB params")
return
}
}
// Map response body to schema
resp.Diagnostics.Append(flattens.K8SCPResource(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s_cp cluster")
return
}
// Set data last update
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End update k8s_cp cluster", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceK8SCP) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Get current state
var state models.ResourceK8SCPModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start delete k8s_cp cluster", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
// Set timeouts
deleteTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout600s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
defer cancel()
var permanently bool
if state.Permanently.IsNull() {
permanently = true
} else {
permanently = state.Permanently.ValueBool()
}
// Delete existing k8s_cp cluster
_, err := r.client.CloudAPI().K8S().Delete(ctx, k8s.DeleteRequest{K8SID: uint64(state.K8SID.ValueInt64()), Permanently: permanently})
if err != nil {
resp.Diagnostics.AddError("Error deleting k8s_cp cluster with error: ", err.Error())
return
}
tflog.Info(ctx, "End delete k8s_cp cluster", map[string]any{"k8s_id": state.K8SID.ValueInt64()})
}
// Schema defines the schema for the resource.
func (r *resourceK8SCP) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaResourceK8SCP(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}),
},
Version: 1,
}
}
// Metadata returns the resource type name.
func (r *resourceK8SCP) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_cp"
}
// Configure adds the provider configured client to the resource.
func (r *resourceK8SCP) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
tflog.Info(ctx, "Get configure resource")
r.client = client.Resource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure resource successfully")
}
func (r *resourceK8SCP) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Retrieve import ID and save to id attribute
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}

View File

@@ -0,0 +1,270 @@
package k8s
import (
"context"
"time"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/schemas"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/utilities"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &resourceK8SWG{}
_ resource.ResourceWithImportState = &resourceK8SWG{}
)
// NewResourceK8S_WG is a helper function to simplify the provider implementation.
func NewResourceK8SWG() resource.Resource {
return &resourceK8SWG{}
}
// resourceK8S_WG is the resource implementation.
type resourceK8SWG struct {
client *decort.DecortClient
}
// Create the resource and sets the initial Terraform state.
func (r *resourceK8SWG) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan models.ResourceK8SWGModel
// Get plan for create cluster
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
tflog.Info(ctx, "Start create k8s_wg", map[string]any{"name": plan.Name.ValueString(), "k8s_id": plan.K8SID.ValueInt64()})
// Set timeouts
createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout20m)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
// Сhecking for values in the platform
resp.Diagnostics.Append(utilities.CheckParamsExistenceWG(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error check input values")
return
}
// Create k8s_wg and validated
resp.Diagnostics.Append(utilities.ResourceK8SWGCreate(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error create k8s_wg")
return
}
// Map response body to schema
resp.Diagnostics.Append(flattens.K8SWGResource(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s_wg")
return
}
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End create k8s_wg cluster", map[string]any{"k8s_id": plan.K8SID.ValueInt64(), "wg_id": plan.Id.ValueString()})
}
// Read refreshes the Terraform state with the latest data.
func (r *resourceK8SWG) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state models.ResourceK8SWGModel
// Get current state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start read k8s_wg", map[string]any{"wg_id": state.Id.ValueString()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout20m)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Overwrite items with refreshed state
resp.Diagnostics.Append(flattens.K8SWGResource(ctx, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s_wg")
return
}
// Set refreshed state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End read k8s_wg", map[string]any{"wg_id": state.Id.ValueString()})
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceK8SWG) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan models.ResourceK8SWGModel
var state models.ResourceK8SWGModel
// Retrieve values from plan
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
// Retrieve values from state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the state")
return
}
tflog.Info(ctx, "Start update k8s_wg", map[string]any{"k8s_id": plan.K8SID.ValueInt64(), "wg_id": plan.WorkerGroupId.ValueInt64()})
// Set timeouts
updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout20m)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, updateTimeout)
defer cancel()
// Сhecking for values in the platform
resp.Diagnostics.Append(utilities.CheckParamsExistenceWG(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error check input values")
return
}
// Update cloud init
if !plan.CloudInit.Equal(state.CloudInit) {
resp.Diagnostics.Append(utilities.K8SWGUpdateCloudInit(ctx, &plan, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error update cloud init")
return
}
}
// Update num workers
if !plan.Num.Equal(state.Num) {
resp.Diagnostics.Append(utilities.K8SWGUpdateNumWorkers(ctx, &plan, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error update num workers")
return
}
}
// Map response body to schema
resp.Diagnostics.Append(flattens.K8SWGResource(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten k8s_wg")
return
}
// Set data last update
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End update k8s_wg", map[string]any{"k8s_id": plan.K8SID.ValueInt64(), "wg_id": plan.WorkerGroupId.ValueInt64()})
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceK8SWG) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Get current state
var state models.ResourceK8SWGModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start delete k8s_wg", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "wg_id": state.WorkerGroupId.ValueInt64()})
// Set timeouts
deleteTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout20m)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
defer cancel()
// Delete existing k8s_wg
_, err := r.client.CloudAPI().K8S().WorkersGroupDelete(ctx, k8s.WorkersGroupDeleteRequest{K8SID: uint64(state.K8SID.ValueInt64()), WorkersGroupID: uint64(state.WorkerGroupId.ValueInt64())})
if err != nil {
resp.Diagnostics.AddError("Error deleting k8s_wg with error: ", err.Error())
return
}
tflog.Info(ctx, "End delete k8s_wg", map[string]any{"k8s_id": state.K8SID.ValueInt64(), "wg_id": state.WorkerGroupId.ValueInt64()})
}
// Schema defines the schema for the resource.
func (r *resourceK8SWG) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaResourceK8SWG(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}),
},
Version: 1,
}
}
// Metadata returns the resource type name.
func (r *resourceK8SWG) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_k8s_wg"
}
// Configure adds the provider configured client to the resource.
func (r *resourceK8SWG) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
tflog.Info(ctx, "Get configure resource")
r.client = client.Resource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure resource successfully")
}
func (r *resourceK8SWG) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Retrieve import ID and save to id attribute
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}

View File

@@ -0,0 +1,82 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceK8ciList() map[string]schema.Attribute {
return map[string]schema.Attribute{
// optional attributes
"by_id": schema.Int64Attribute{
Optional: true,
},
"name": schema.StringAttribute{
Optional: true,
},
"status": schema.StringAttribute{
Optional: true,
},
"worker_driver": schema.StringAttribute{
Optional: true,
},
"master_driver": schema.StringAttribute{
Optional: true,
},
"network_plugins": schema.StringAttribute{
Optional: true,
},
"include_disabled": schema.BoolAttribute{
Optional: true,
},
"sort_by": schema.StringAttribute{
Optional: true,
Description: "sort by one of supported fields, format +|-(field)",
},
"page": schema.Int64Attribute{
Optional: true,
},
"size": schema.Int64Attribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"items": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"k8ci_id": schema.Int64Attribute{
Computed: true,
},
"k8ci_name": schema.StringAttribute{
Computed: true,
},
"lb_image_id": schema.Int64Attribute{
Computed: true,
},
"network_plugins": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"status": schema.StringAttribute{
Computed: true,
},
"desc": schema.StringAttribute{
Computed: true,
},
"created_time": schema.Int64Attribute{
Computed: true,
},
"version": schema.StringAttribute{
Computed: true,
},
},
},
},
"entry_count": schema.Int64Attribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,304 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceK8S() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"k8s_id": schema.Int64Attribute{
Required: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"acl": schema.SingleNestedAttribute{
Computed: true,
Attributes: map[string]schema.Attribute{
"account_acl": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"explicit": schema.BoolAttribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"right": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"type": schema.StringAttribute{
Computed: true,
},
"user_group_id": schema.StringAttribute{
Computed: true,
},
},
},
},
"k8s_acl": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"explicit": schema.BoolAttribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"right": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"type": schema.StringAttribute{
Computed: true,
},
"user_group_id": schema.StringAttribute{
Computed: true,
},
},
},
},
"rg_acl": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"explicit": schema.BoolAttribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"right": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"type": schema.StringAttribute{
Computed: true,
},
"user_group_id": schema.StringAttribute{
Computed: true,
},
},
},
},
},
},
"account_id": schema.Int64Attribute{
Computed: true,
},
"account_name": schema.StringAttribute{
Computed: true,
},
"bservice_id": schema.Int64Attribute{
Computed: true,
},
"k8sci_id": schema.Int64Attribute{
Computed: true,
},
"created_by": schema.StringAttribute{
Computed: true,
},
"created_time": schema.Int64Attribute{
Computed: true,
},
"deleted_by": schema.StringAttribute{
Computed: true,
},
"deleted_time": schema.Int64Attribute{
Computed: true,
},
"extnet_id": schema.Int64Attribute{
Computed: true,
},
"k8sci_name": schema.StringAttribute{
Computed: true,
},
"masters": schema.SingleNestedAttribute{
Computed: true,
Attributes: map[string]schema.Attribute{
"cpu": schema.Int64Attribute{
Computed: true,
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"interfaces": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"def_gw": schema.StringAttribute{
Computed: true,
},
"ip_address": schema.StringAttribute{
Computed: true,
},
},
},
},
"natable_vins_ip": schema.StringAttribute{
Computed: true,
},
"natable_vins_network": schema.StringAttribute{
Computed: true,
},
},
},
},
"disk": schema.Int64Attribute{
Computed: true,
},
"master_group_id": schema.Int64Attribute{
Computed: true,
},
"master_group_name": schema.StringAttribute{
Computed: true,
},
"num": schema.Int64Attribute{
Computed: true,
},
"ram": schema.Int64Attribute{
Computed: true,
},
},
},
"workers": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"annotations": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"cpu": schema.Int64Attribute{
Computed: true,
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"interfaces": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"def_gw": schema.StringAttribute{
Computed: true,
},
"ip_address": schema.StringAttribute{
Computed: true,
},
},
},
},
"natable_vins_ip": schema.StringAttribute{
Computed: true,
},
"natable_vins_network": schema.StringAttribute{
Computed: true,
},
},
},
},
"disk": schema.Int64Attribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"worker_group_id": schema.Int64Attribute{
Computed: true,
},
"labels": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"worker_group_name": schema.StringAttribute{
Computed: true,
},
"num": schema.Int64Attribute{
Computed: true,
},
"ram": schema.Int64Attribute{
Computed: true,
},
"taints": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
},
},
},
"lb_id": schema.Int64Attribute{
Computed: true,
},
"lb_ip": schema.StringAttribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"network_plugin": schema.StringAttribute{
Computed: true,
},
"rg_id": schema.Int64Attribute{
Computed: true,
},
"rg_name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"updated_by": schema.StringAttribute{
Computed: true,
},
"updated_time": schema.Int64Attribute{
Computed: true,
},
"kubeconfig": schema.StringAttribute{
Computed: true,
},
"vins_id": schema.Int64Attribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,62 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
)
func MakeSchemaDataSourceK8SComputes() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"k8s_id": schema.Int64Attribute{
Required: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"masters": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"group_name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
},
},
},
"workers": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"group_name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
},
},
},
}
}

View File

@@ -0,0 +1,215 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceK8SList() map[string]schema.Attribute {
return map[string]schema.Attribute{
// optional attributes
"by_id": schema.Int64Attribute{
Optional: true,
},
"name": schema.StringAttribute{
Optional: true,
},
"ip_address": schema.StringAttribute{
Optional: true,
},
"rg_id": schema.Int64Attribute{
Optional: true,
},
"lb_id": schema.Int64Attribute{
Optional: true,
},
"bservice_id": schema.Int64Attribute{
Optional: true,
},
"status": schema.StringAttribute{
Optional: true,
},
"tech_status": schema.StringAttribute{
Optional: true,
},
"includedeleted": schema.BoolAttribute{
Optional: true,
},
"sort_by": schema.StringAttribute{
Optional: true,
Description: "sort by one of supported fields, format +|-(field)",
},
"page": schema.Int64Attribute{
Optional: true,
},
"size": schema.Int64Attribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"items": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"account_id": schema.Int64Attribute{
Computed: true,
},
"account_name": schema.StringAttribute{
Computed: true,
},
"acl": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"bservice_id": schema.Int64Attribute{
Computed: true,
},
"k8sci_id": schema.Int64Attribute{
Computed: true,
},
"created_by": schema.StringAttribute{
Computed: true,
},
"created_time": schema.Int64Attribute{
Computed: true,
},
"deleted_by": schema.StringAttribute{
Computed: true,
},
"deleted_time": schema.Int64Attribute{
Computed: true,
},
"desc": schema.StringAttribute{
Computed: true,
},
"extnet_id": schema.Int64Attribute{
Computed: true,
},
"gid": schema.Int64Attribute{
Computed: true,
},
"guid": schema.Int64Attribute{
Computed: true,
},
"k8s_id": schema.Int64Attribute{
Computed: true,
},
"lb_id": schema.Int64Attribute{
Computed: true,
},
"milestones": schema.Int64Attribute{
Computed: true,
},
"k8s_name": schema.StringAttribute{
Computed: true,
},
"network_plugin": schema.StringAttribute{
Computed: true,
},
"rg_id": schema.Int64Attribute{
Computed: true,
},
"rg_name": schema.StringAttribute{
Computed: true,
},
"service_account": schema.SingleNestedAttribute{
Computed: true,
Attributes: map[string]schema.Attribute{
"guid": schema.StringAttribute{
Computed: true,
},
"password": schema.StringAttribute{
Computed: true,
},
"username": schema.StringAttribute{
Computed: true,
},
},
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"updated_by": schema.StringAttribute{
Computed: true,
},
"updated_time": schema.Int64Attribute{
Computed: true,
},
"vins_id": schema.Int64Attribute{
Computed: true,
},
"workers_groups": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"annotations": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"cpu": schema.Int64Attribute{
Computed: true,
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"externalip": schema.StringAttribute{
Computed: true,
},
"id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
},
},
},
"disk": schema.Int64Attribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"worker_group_id": schema.Int64Attribute{
Computed: true,
},
"labels": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"worker_group_name": schema.StringAttribute{
Computed: true,
},
"num": schema.Int64Attribute{
Computed: true,
},
"ram": schema.Int64Attribute{
Computed: true,
},
"taints": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
},
},
},
},
},
},
"entry_count": schema.Int64Attribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,209 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceK8SListDeleted() map[string]schema.Attribute {
return map[string]schema.Attribute{
// optional attributes
"by_id": schema.Int64Attribute{
Optional: true,
},
"name": schema.StringAttribute{
Optional: true,
},
"ip_address": schema.StringAttribute{
Optional: true,
},
"rg_id": schema.Int64Attribute{
Optional: true,
},
"lb_id": schema.Int64Attribute{
Optional: true,
},
"bservice_id": schema.Int64Attribute{
Optional: true,
},
"tech_status": schema.StringAttribute{
Optional: true,
},
"sort_by": schema.StringAttribute{
Optional: true,
Description: "sort by one of supported fields, format +|-(field)",
},
"page": schema.Int64Attribute{
Optional: true,
},
"size": schema.Int64Attribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"items": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"account_id": schema.Int64Attribute{
Computed: true,
},
"account_name": schema.StringAttribute{
Computed: true,
},
"acl": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"bservice_id": schema.Int64Attribute{
Computed: true,
},
"k8sci_id": schema.Int64Attribute{
Computed: true,
},
"created_by": schema.StringAttribute{
Computed: true,
},
"created_time": schema.Int64Attribute{
Computed: true,
},
"deleted_by": schema.StringAttribute{
Computed: true,
},
"deleted_time": schema.Int64Attribute{
Computed: true,
},
"desc": schema.StringAttribute{
Computed: true,
},
"extnet_id": schema.Int64Attribute{
Computed: true,
},
"gid": schema.Int64Attribute{
Computed: true,
},
"guid": schema.Int64Attribute{
Computed: true,
},
"k8s_id": schema.Int64Attribute{
Computed: true,
},
"lb_id": schema.Int64Attribute{
Computed: true,
},
"milestones": schema.Int64Attribute{
Computed: true,
},
"k8s_name": schema.StringAttribute{
Computed: true,
},
"network_plugin": schema.StringAttribute{
Computed: true,
},
"rg_id": schema.Int64Attribute{
Computed: true,
},
"rg_name": schema.StringAttribute{
Computed: true,
},
"service_account": schema.SingleNestedAttribute{
Computed: true,
Attributes: map[string]schema.Attribute{
"guid": schema.StringAttribute{
Computed: true,
},
"password": schema.StringAttribute{
Computed: true,
},
"username": schema.StringAttribute{
Computed: true,
},
},
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"updated_by": schema.StringAttribute{
Computed: true,
},
"updated_time": schema.Int64Attribute{
Computed: true,
},
"vins_id": schema.Int64Attribute{
Computed: true,
},
"workers_groups": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"annotations": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"cpu": schema.Int64Attribute{
Computed: true,
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"externalip": schema.StringAttribute{
Computed: true,
},
"id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
},
},
},
"disk": schema.Int64Attribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"worker_group_id": schema.Int64Attribute{
Computed: true,
},
"labels": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"worker_group_name": schema.StringAttribute{
Computed: true,
},
"num": schema.Int64Attribute{
Computed: true,
},
"ram": schema.Int64Attribute{
Computed: true,
},
"taints": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
},
},
},
},
},
},
"entry_count": schema.Int64Attribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,90 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceK8SWg() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"k8s_id": schema.Int64Attribute{
Required: true,
},
"wg_id": schema.Int64Attribute{
Required: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"annotations": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"cpu": schema.Int64Attribute{
Computed: true,
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"interfaces": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"def_gw": schema.StringAttribute{
Computed: true,
},
"ip_address": schema.StringAttribute{
Computed: true,
},
},
},
},
"natable_vins_ip": schema.StringAttribute{
Computed: true,
},
"natable_vins_network": schema.StringAttribute{
Computed: true,
},
},
},
},
"disk": schema.Int64Attribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"labels": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"worker_group_name": schema.StringAttribute{
Computed: true,
},
"num": schema.Int64Attribute{
Computed: true,
},
"ram": schema.Int64Attribute{
Computed: true,
},
"taints": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
}
}

View File

@@ -0,0 +1,24 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
)
func MakeSchemaDataSourceK8SWgCloudInit() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"k8s_id": schema.Int64Attribute{
Required: true,
},
"wg_id": schema.Int64Attribute{
Required: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"cloud_init": schema.StringAttribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,97 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceK8SWgList() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"k8s_id": schema.Int64Attribute{
Required: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"items": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"annotations": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"cpu": schema.Int64Attribute{
Computed: true,
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"interfaces": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"def_gw": schema.StringAttribute{
Computed: true,
},
"ip_address": schema.StringAttribute{
Computed: true,
},
},
},
},
"natable_vins_ip": schema.StringAttribute{
Computed: true,
},
"natable_vins_network": schema.StringAttribute{
Computed: true,
},
},
},
},
"disk": schema.Int64Attribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"labels": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"worker_group_id": schema.Int64Attribute{
Computed: true,
},
"worker_group_name": schema.StringAttribute{
Computed: true,
},
"num": schema.Int64Attribute{
Computed: true,
},
"ram": schema.Int64Attribute{
Computed: true,
},
"taints": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
},
},
},
}
}

View File

@@ -0,0 +1,354 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/validate"
)
func MakeSchemaResourceK8SCP() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"name": schema.StringAttribute{
Required: true,
Description: "Name of the cluster.",
},
"rg_id": schema.Int64Attribute{
Required: true,
Description: "Resource group ID that this instance belongs to.",
},
"k8sci_id": schema.Int64Attribute{
Required: true,
Description: "ID of the k8s catalog item to base this instance on.",
},
"network_plugin": schema.StringAttribute{
Required: true,
Validators: []validator.String{
stringvalidator.OneOf("flannel", "weavenet", "calico"),
},
Description: "Network plugin to be used",
},
// optional attributes for create
"sep_id": schema.Int64Attribute{
Optional: true,
Description: "Storage Endpoint ID",
},
"sep_pool": schema.StringAttribute{
Optional: true,
Description: "Storage Endpoint Pool",
},
"num": schema.Int64Attribute{
Optional: true,
Computed: true,
Validators: []validator.Int64{
int64validator.OneOf(1, 3, 5),
},
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
Description: "Number of VMs to create. Can be either 1,3 or 5",
},
"cpu": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "Node CPU count.",
},
"ram": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "Node RAM in MB.",
Validators: []validator.Int64{
validate.DivisibleBy(constants.DivisibleByRAM),
},
},
"disk": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "Node boot disk size in GB.",
},
"extnet_id": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "ID of the external network to connect workers to. If omitted network will be chosen by the platfom.",
},
"vins_id": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "ID of default vins for this instace.",
},
"with_lb": schema.BoolAttribute{
Optional: true,
Description: "Create k8s with load balancer if true.",
},
"ha_mode": schema.BoolAttribute{
Optional: true,
Description: "Use Highly Available schema for LB deploy",
},
"additional_sans": schema.ListAttribute{
Optional: true,
ElementType: types.StringType,
Description: "is used to define settings and actions that should be performed before any other component in the cluster starts. It allows you to configure things like node registration, network setup, and other initialization tasks. insert a valid JSON string with all levels of nesting.",
},
"init_config": schema.StringAttribute{
Optional: true,
Description: "is used to define settings and actions that should be performed before any other component in the cluster starts. It allows you to configure things like node registration, network setup, and other initialization tasks. insert a valid JSON string with all levels of nesting.",
},
"cluster_config": schema.StringAttribute{
Optional: true,
Description: "is used to configure the behavior and settings of the Kube-proxy, which is responsible for network proxying and load balancing within the cluster. It includes parameters such as proxy mode, cluster IP ranges, and other Kube-proxy specific configurations. insert a valid JSON string with all levels of nesting.",
},
"kubelet_config": schema.StringAttribute{
Optional: true,
Description: "is used to configure the behavior and settings of the Kube-proxy, which is responsible for network proxying and load balancing within the cluster. It includes parameters such as proxy mode, cluster IP ranges, and other Kube-proxy specific configurations. insert a valid JSON string with all levels of nesting.",
},
"kube_proxy_config": schema.StringAttribute{
Optional: true,
Description: "is used to configure the behavior and settings of the Kube-proxy, which is responsible for network proxying and load balancing within the cluster. It includes parameters such as proxy mode, cluster IP ranges, and other Kube-proxy specific configurations. insert a valid JSON string with all levels of nesting.",
},
"join_config": schema.StringAttribute{
Optional: true,
Description: "is used to configure the behavior and settings for joining a node to a cluster. It includes parameters such as the cluster's control plane endpoint, token, and certificate key. insert a valid JSON string with all levels of nesting.",
},
"desc": schema.StringAttribute{
Optional: true,
Description: "Text description of this instance.",
},
"extnet_only": schema.BoolAttribute{
Optional: true,
Description: "Use only selected ExtNet for infrastructure connections",
},
"oidc_cert": schema.StringAttribute{
Optional: true,
Description: "insert ssl certificate in x509 pem format",
},
"lb_sysctl_params": schema.ListNestedAttribute{
Optional: true,
Description: "Custom sysctl values for Load Balancer instance. Applied on boot.",
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"key": schema.StringAttribute{
Required: true,
},
"value": schema.StringAttribute{
Required: true,
},
},
},
},
// optional attributes for update
"start": schema.BoolAttribute{
Optional: true,
Description: "Start k8s cluster.",
},
"enabled": schema.BoolAttribute{
Optional: true,
Description: "Enable k8s cluster",
},
"permanently": schema.BoolAttribute{
Optional: true,
Description: "whether to completely delete the k8s cluster",
},
"restore": schema.BoolAttribute{
Optional: true,
Description: "if true, restore the k8s cluster from Recycle Bin",
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"last_updated": schema.StringAttribute{
Computed: true,
Description: "Timestamp of the last Terraform update of the order.",
},
"master_group_id": schema.Int64Attribute{
Computed: true,
Description: "Master group ID.",
},
"master_group_name": schema.StringAttribute{
Computed: true,
Description: "Master group name.",
},
"acl": schema.SingleNestedAttribute{
Computed: true,
Attributes: map[string]schema.Attribute{
"account_acl": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"explicit": schema.BoolAttribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"right": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"type": schema.StringAttribute{
Computed: true,
},
"user_group_id": schema.StringAttribute{
Computed: true,
},
},
},
},
"k8s_acl": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"explicit": schema.BoolAttribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"right": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"type": schema.StringAttribute{
Computed: true,
},
"user_group_id": schema.StringAttribute{
Computed: true,
},
},
},
},
"rg_acl": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"explicit": schema.BoolAttribute{
Computed: true,
},
"guid": schema.StringAttribute{
Computed: true,
},
"right": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"type": schema.StringAttribute{
Computed: true,
},
"user_group_id": schema.StringAttribute{
Computed: true,
},
},
},
},
},
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"interfaces": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"def_gw": schema.StringAttribute{
Computed: true,
},
"ip_address": schema.StringAttribute{
Computed: true,
},
},
},
},
"natable_vins_ip": schema.StringAttribute{
Computed: true,
},
"natable_vins_network": schema.StringAttribute{
Computed: true,
},
},
},
},
"account_id": schema.Int64Attribute{
Computed: true,
},
"account_name": schema.StringAttribute{
Computed: true,
},
"bservice_id": schema.Int64Attribute{
Computed: true,
},
"created_by": schema.StringAttribute{
Computed: true,
},
"created_time": schema.Int64Attribute{
Computed: true,
},
"deleted_by": schema.StringAttribute{
Computed: true,
},
"deleted_time": schema.Int64Attribute{
Computed: true,
},
"k8s_ci_name": schema.StringAttribute{
Computed: true,
},
"lb_id": schema.Int64Attribute{
Computed: true,
},
"k8s_id": schema.Int64Attribute{
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"lb_ip": schema.StringAttribute{
Computed: true,
},
"rg_name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"updated_by": schema.StringAttribute{
Computed: true,
},
"updated_time": schema.Int64Attribute{
Computed: true,
},
"kubeconfig": schema.StringAttribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,132 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/validate"
)
func MakeSchemaResourceK8SWG() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"k8s_id": schema.Int64Attribute{
Required: true,
Description: "ID of k8s instance.",
},
"name": schema.StringAttribute{
Required: true,
Description: "Name of the worker group.",
},
// optional attributes
"num": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "Number of worker nodes to create.",
},
"cpu": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "Worker node CPU count.",
},
"ram": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "Worker node RAM in MB.",
Validators: []validator.Int64{
validate.DivisibleBy(constants.DivisibleByRAM),
},
},
"disk": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "Worker node boot disk size. If unspecified or 0, size is defined by OS image size.",
},
"labels": schema.ListAttribute{
Optional: true,
Computed: true,
ElementType: types.StringType,
},
"annotations": schema.ListAttribute{
Optional: true,
Computed: true,
ElementType: types.StringType,
},
"taints": schema.ListAttribute{
Optional: true,
Computed: true,
ElementType: types.StringType,
},
"worker_sep_id": schema.Int64Attribute{
Optional: true,
},
"worker_sep_pool": schema.StringAttribute{
Optional: true,
},
"cloud_init": schema.StringAttribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"last_updated": schema.StringAttribute{
Computed: true,
Description: "Timestamp of the last Terraform update of the order.",
},
"wg_id": schema.Int64Attribute{
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"detailed_info": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"compute_id": schema.Int64Attribute{
Computed: true,
},
"name": schema.StringAttribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"interfaces": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"def_gw": schema.StringAttribute{
Computed: true,
},
"ip_address": schema.StringAttribute{
Computed: true,
},
},
},
},
"natable_vins_ip": schema.StringAttribute{
Computed: true,
},
"natable_vins_network": schema.StringAttribute{
Computed: true,
},
},
},
},
"guid": schema.StringAttribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,42 @@
package utilities
import (
"context"
"github.com/hashicorp/terraform-plugin-framework/diag"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/ic"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
)
func CheckParamsExistenceCP(ctx context.Context, plan *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
diags := diag.Diagnostics{}
if err := ic.ExistRG(ctx, uint64(plan.RGID.ValueInt64()), c); err != nil {
diags.AddError("Error check input values", err.Error())
}
if err := ic.ExistK8CI(ctx, uint64(plan.K8SCIID.ValueInt64()), c); err != nil {
diags.AddError("Error check input values", err.Error())
}
if err := ic.ExistExtNetInK8s(ctx, uint64(plan.ExtNetID.ValueInt64()), c); err != nil {
diags.AddError("Error check input values", err.Error())
}
if err := ic.ExistVinsInK8s(ctx, uint64(plan.VinsId.ValueInt64()), c); err != nil {
diags.AddError("Error check input values", err.Error())
}
return diags
}
func CheckParamsExistenceWG(ctx context.Context, plan *models.ResourceK8SWGModel, c *decort.DecortClient) diag.Diagnostics {
diags := diag.Diagnostics{}
if err := ic.ExistK8s(ctx, uint64(plan.K8SID.ValueInt64()), c); err != nil {
diags.AddError("Error check input values", err.Error())
}
return diags
}

View File

@@ -0,0 +1,55 @@
package utilities
import (
"context"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8ci"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
)
func K8ciListCheckPresence(ctx context.Context, state *models.K8ciListModel, c *decort.DecortClient) (*k8ci.ListK8CI, error) {
tflog.Info(ctx, "Get k8ci list info")
req := k8ci.ListRequest{}
if !state.ByID.IsNull() {
req.ByID = uint64(state.ByID.ValueInt64())
}
if !state.Name.IsNull() {
req.Name = state.Name.ValueString()
}
if !state.Status.IsNull() {
req.Status = state.Status.ValueString()
}
if !state.WorkerDriver.IsNull() {
req.WorkerDriver = state.WorkerDriver.ValueString()
}
if !state.MasterDriver.IsNull() {
req.MasterDriver = state.MasterDriver.ValueString()
}
if !state.NetworkPlugins.IsNull() {
req.NetworkPlugins = state.NetworkPlugins.ValueString()
}
if !state.IncludeDisabled.IsNull() {
req.IncludeDisabled = state.IncludeDisabled.ValueBool()
}
if !state.SortBy.IsNull() {
req.SortBy = state.SortBy.ValueString()
}
if !state.Size.IsNull() {
req.Size = uint64(state.Size.ValueInt64())
}
if !state.Page.IsNull() {
req.Page = uint64(state.Page.ValueInt64())
}
k8sList, err := c.CloudAPI().K8CI().List(ctx, req)
if err != nil {
return nil, err
}
tflog.Info(ctx, "Getting k8ci list info, successfully")
return k8sList, nil
}

View File

@@ -0,0 +1,61 @@
package utilities
import (
"context"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
)
func K8sListCheckPresence(ctx context.Context, state *models.K8SListModel, c *decort.DecortClient) (*k8s.ListK8SClusters, error) {
tflog.Info(ctx, "Get k8s list info")
req := k8s.ListRequest{}
if !state.ByID.IsNull() {
req.ByID = uint64(state.ByID.ValueInt64())
}
if !state.Name.IsNull() {
req.Name = state.Name.ValueString()
}
if !state.IPAddress.IsNull() {
req.IPAddress = state.IPAddress.ValueString()
}
if !state.RGID.IsNull() {
req.RGID = uint64(state.RGID.ValueInt64())
}
if !state.LBID.IsNull() {
req.LBID = uint64(state.LBID.ValueInt64())
}
if !state.BasicServiceID.IsNull() {
req.BasicServiceID = uint64(state.BasicServiceID.ValueInt64())
}
if !state.Status.IsNull() {
req.Status = state.Status.ValueString()
}
if !state.TechStatus.IsNull() {
req.TechStatus = state.TechStatus.ValueString()
}
if !state.IncludeDeleted.IsNull() {
req.IncludeDeleted = state.IncludeDeleted.ValueBool()
}
if !state.SortBy.IsNull() {
req.SortBy = state.SortBy.ValueString()
}
if !state.Size.IsNull() {
req.Size = uint64(state.Size.ValueInt64())
}
if !state.Page.IsNull() {
req.Page = uint64(state.Page.ValueInt64())
}
k8sList, err := c.CloudAPI().K8S().List(ctx, req)
if err != nil {
return nil, err
}
tflog.Info(ctx, "Getting k8s list info, successfully")
return k8sList, nil
}

View File

@@ -0,0 +1,55 @@
package utilities
import (
"context"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
)
func K8sListDeletedCheckPresence(ctx context.Context, state *models.K8SListDeletedModel, c *decort.DecortClient) (*k8s.ListK8SClusters, error) {
tflog.Info(ctx, "Get k8s list deleted info")
req := k8s.ListDeletedRequest{}
if !state.ByID.IsNull() {
req.ByID = uint64(state.ByID.ValueInt64())
}
if !state.Name.IsNull() {
req.Name = state.Name.ValueString()
}
if !state.IPAddress.IsNull() {
req.IPAddress = state.IPAddress.ValueString()
}
if !state.RGID.IsNull() {
req.RGID = uint64(state.RGID.ValueInt64())
}
if !state.LBID.IsNull() {
req.LBID = uint64(state.LBID.ValueInt64())
}
if !state.BasicServiceID.IsNull() {
req.BasicServiceID = uint64(state.BasicServiceID.ValueInt64())
}
if !state.TechStatus.IsNull() {
req.TechStatus = state.TechStatus.ValueString()
}
if !state.SortBy.IsNull() {
req.SortBy = state.SortBy.ValueString()
}
if !state.Size.IsNull() {
req.Size = uint64(state.Size.ValueInt64())
}
if !state.Page.IsNull() {
req.Page = uint64(state.Page.ValueInt64())
}
k8sList, err := c.CloudAPI().K8S().ListDeleted(ctx, req)
if err != nil {
return nil, err
}
tflog.Info(ctx, "Getting k8s list deleted info, successfully")
return k8sList, nil
}

View File

@@ -0,0 +1,488 @@
package utilities
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/status"
)
func CreateRequestResourceK8CP(ctx context.Context, plan *models.ResourceK8SCPModel) k8s.CreateRequest {
tflog.Info(ctx, "Start CreateRequestResourceK8CP", map[string]any{"name": plan.Name.ValueString()})
req := k8s.CreateRequest{
Name: plan.Name.ValueString(),
RGID: uint64(plan.RGID.ValueInt64()),
K8SCIID: uint64(plan.K8SCIID.ValueInt64()),
WorkerGroupName: "temp",
NetworkPlugin: plan.NetworkPlugin.ValueString(),
}
if !plan.Num.IsUnknown() {
req.MasterNum = uint(plan.Num.ValueInt64())
}
if !plan.CPU.IsUnknown() {
req.MasterCPU = uint(plan.CPU.ValueInt64())
}
if !plan.RAM.IsUnknown() {
req.MasterRAM = uint64(plan.RAM.ValueInt64())
}
if !plan.Disk.IsUnknown() {
req.MasterDisk = uint(plan.Disk.ValueInt64())
}
if !plan.SEPID.IsNull() {
req.MasterSEPID = uint64(plan.SEPID.ValueInt64())
}
if !plan.SEPPool.IsNull() {
req.MasterSEPPool = plan.SEPPool.ValueString()
}
if !plan.WithLB.IsNull() {
req.WithLB = plan.WithLB.ValueBool()
} else {
req.WithLB = true
}
if !plan.ExtNetID.IsUnknown() {
req.ExtNetID = uint64(plan.ExtNetID.ValueInt64())
}
if !plan.VinsId.IsUnknown() {
req.VinsId = uint64(plan.VinsId.ValueInt64())
}
if !plan.HighlyAvailable.IsNull() {
req.HighlyAvailable = plan.HighlyAvailable.ValueBool()
}
if !plan.AdditionalSANs.IsNull() {
result := make([]string, 0, len(plan.AdditionalSANs.Elements()))
for _, val := range plan.AdditionalSANs.Elements() {
result = append(result, strings.Trim(val.String(), "\""))
}
req.AdditionalSANs = result
}
if !plan.ClusterConfiguration.IsNull() {
req.ClusterConfiguration = plan.ClusterConfiguration.ValueString()
}
if !plan.KubeletConfiguration.IsNull() {
req.KubeletConfiguration = plan.KubeletConfiguration.ValueString()
}
if !plan.KubeProxyConfiguration.IsNull() {
req.KubeProxyConfiguration = plan.KubeProxyConfiguration.ValueString()
}
if !plan.InitConfiguration.IsNull() {
req.InitConfiguration = plan.InitConfiguration.ValueString()
}
if !plan.OidcCertificate.IsNull() {
req.OidcCertificate = plan.OidcCertificate.ValueString()
}
if !plan.Description.IsNull() {
req.Description = plan.Description.ValueString()
}
if !plan.ExtNetOnly.IsNull() {
req.ExtNetOnly = plan.ExtNetOnly.ValueBool()
}
if !plan.LBSysctlParams.IsNull() {
result := make([]map[string]interface{}, 0, len(plan.LBSysctlParams.Elements()))
for _, val := range plan.LBSysctlParams.Elements() {
objVal := val.(types.Object)
valMap := objVal.Attributes()
mapKey := valMap["key"].(types.String).ValueString()
mapVal := valMap["value"].(types.String).ValueString()
tempMap := make(map[string]interface{})
tempMap[mapKey] = mapVal
result = append(result, tempMap)
}
req.LbSysctlParams = result
}
tflog.Info(ctx, "End CreateRequestResourceK8CP", map[string]any{"name": plan.Name.String()})
return req
}
func CheckResourceK8SCPCreateAndDeleteWG(ctx context.Context, plan *models.ResourceK8SCPModel, c *decort.DecortClient, resp string) diag.Diagnostics {
tflog.Info(ctx, "Start CheckResourceK8CPCreateAndDeleteWG", map[string]any{"name": plan.Name.ValueString()})
diags := diag.Diagnostics{}
taskReq := tasks.GetRequest{
AuditID: strings.Trim(resp, `"`),
}
for {
task, err := c.CloudAPI().Tasks().Get(ctx, taskReq)
if err != nil {
diags.AddError("The audit cannot be found", err.Error())
return diags
}
tflog.Info(ctx, fmt.Sprintf("ResourceK8sControlPlaneCreate instance creating - %s", task.Stage))
if task.Completed {
if task.Error != "" {
diags.AddError("Cannot create cluster instance:", task.Error)
return diags
}
result, err := task.Result.ID()
if err != nil {
diags.AddError("Cannot get cluster ID:", err.Error())
return diags
}
plan.Id = types.StringValue(strconv.Itoa(result))
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
break
}
time.Sleep(time.Second * 20)
}
k8sID, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError("Cannot parsed ID cluster from state", err.Error())
return diags
}
cluster, err := K8SCPResourceCheckPresence(ctx, k8sID, c)
if err != nil {
diags.AddError("Cannot get info about cluster ", err.Error())
return diags
}
tflog.Info(ctx, "Start delete Work Group from cluster with ID", map[string]any{"k8s_id": k8sID})
delWGReq := k8s.WorkersGroupDeleteRequest{
K8SID: cluster.ID,
WorkersGroupID: cluster.K8SGroups.Workers[0].ID,
}
_, err = c.CloudAPI().K8S().WorkersGroupDelete(ctx, delWGReq)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot create cluster with ID - %d: platform error, creation cancelled, cluster will be delete permanently", cluster.ID), err.Error())
tflog.Error(ctx, "Start delete cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
_, err = c.CloudAPI().K8S().Delete(ctx, k8s.DeleteRequest{K8SID: cluster.ID, Permanently: true})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot delete cluster with ID - %d, after error creation. Please report this issue to the provider developers.", cluster.ID), err.Error())
return diags
}
tflog.Error(ctx, "Delete cluster successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
tflog.Info(ctx, "End CheckResourceK8CPCreateAndDeleteWG", map[string]any{"k8s_id": cluster.ID})
return diags
}
func K8SCPResourceCheckPresence(ctx context.Context, k8SID uint64, c *decort.DecortClient) (*k8s.RecordK8S, error) {
tflog.Info(ctx, "Get info about cluster with ID", map[string]any{"k8s_id": k8SID})
cluster, err := c.CloudAPI().K8S().Get(ctx, k8s.GetRequest{K8SID: k8SID})
if err != nil {
return nil, fmt.Errorf("cannot get info about cluster with error: %w", err)
}
tflog.Info(ctx, "Getting info about cluster successfully", map[string]any{"k8s_id": k8SID})
return cluster, nil
}
func K8sListForResourceCheckPresence(ctx context.Context, k8SID uint64, c *decort.DecortClient) (*k8s.ListK8SClusters, error) {
tflog.Info(ctx, "Get info in List about cluster with ID", map[string]any{"k8s_id": k8SID})
req := k8s.ListRequest{
IncludeDeleted: false,
ByID: k8SID,
}
k8sList, err := c.CloudAPI().K8S().List(ctx, req)
if err != nil {
return nil, err
}
tflog.Info(ctx, "Getting info in List about cluster successfully", map[string]any{"k8s_id": k8SID})
return k8sList, nil
}
func ComputeCheckPresence(ctx context.Context, computeID uint64, c *decort.DecortClient) (*compute.RecordCompute, error) {
tflog.Info(ctx, "Start utilityComputeCheckPresence", map[string]any{"compute_id": computeID})
req := compute.GetRequest{
ComputeID: computeID,
}
compute, err := c.CloudAPI().Compute().Get(ctx, req)
if err != nil {
return nil, err
}
tflog.Info(ctx, "End utilityComputeCheckPresence", map[string]any{"compute_id": computeID})
return compute, nil
}
func K8SCPUpdateNameOrDescription(ctx context.Context, plan, state *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Update info about cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
k8sID, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError("Cannot parsed ID cluster from state", err.Error())
return diags
}
req := k8s.UpdateRequest{
K8SID: k8sID,
}
if !plan.Name.Equal(state.Name) {
req.Name = plan.Name.ValueString()
}
if !plan.Description.Equal(state.Description) {
req.Description = plan.Description.ValueString()
}
_, err = c.CloudAPI().K8S().Update(ctx, req)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot update cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
tflog.Info(ctx, "Update info about cluster successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
func K8SCPReadStatus(ctx context.Context, plan *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Read status cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
k8sID, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError("Cannot parsed ID cluster from state", err.Error())
return diags
}
cluster, err := K8SCPResourceCheckPresence(ctx, k8sID, c)
if err != nil {
diags.AddError("Cannot get info about cluster ", err.Error())
return diags
}
switch cluster.Status {
case status.Modeled:
diags.AddError("Error:", fmt.Sprintf("The k8s cluster is in status: %s, please, contact support for more information", cluster.Status))
return diags
case status.Deleted:
if plan.Restore.ValueBool() || plan.Restore.IsNull() {
diags = K8SCPRestore(ctx, plan, c)
if diags.HasError() {
tflog.Error(ctx, "Error restore cluster", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
} else {
diags.AddError("Cluster in status Deleted:", "please clean state, or restore cluster")
return diags
}
if plan.Enabled.ValueBool() || plan.Enabled.IsNull() {
diags = K8SCPEnableDisable(ctx, plan, c)
if diags.HasError() {
tflog.Error(ctx, "Error enable/disable cluster", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
if plan.Start.ValueBool() || plan.Start.IsNull() {
diags = K8SCPStartStop(ctx, plan, c)
if diags.HasError() {
tflog.Error(ctx, "Error start/stop cluster", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
}
}
case status.Destroying:
diags.AddError("Error:", fmt.Sprintf("The k8s cluster is in progress with status: %s", cluster.Status))
return diags
case status.Destroyed:
diags.AddError("Error:", "The resource cannot be updated because it has been destroyed")
return diags
}
tflog.Info(ctx, "Read status cluster successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
func K8SCPRestore(ctx context.Context, plan *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Restore cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
k8sID, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError("Cannot parsed ID cluster from state", err.Error())
return diags
}
_, err = c.CloudAPI().K8S().Restore(ctx, k8s.RestoreRequest{K8SID: k8sID})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot restore cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
tflog.Info(ctx, "Restore cluster successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
func K8SCPEnableDisable(ctx context.Context, plan *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Enable/Disable cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
k8sID, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError("Cannot parsed ID cluster from state", err.Error())
return diags
}
if plan.Enabled.ValueBool() || plan.Enabled.IsNull() {
_, err := c.CloudAPI().K8S().Enable(ctx, k8s.DisableEnableRequest{K8SID: k8sID})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot enable cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
}
if !plan.Enabled.ValueBool() && !plan.Enabled.IsNull() {
_, err := c.CloudAPI().K8S().Disable(ctx, k8s.DisableEnableRequest{K8SID: k8sID})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot disable cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
}
tflog.Info(ctx, "Enable/Disable cluster successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
func K8SCPStartStop(ctx context.Context, plan *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start/Stop cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
k8sID, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError("Cannot parsed ID cluster from state", err.Error())
return diags
}
if plan.Enabled.ValueBool() || plan.Enabled.IsNull() {
if plan.Start.ValueBool() || plan.Start.IsNull() {
_, err := c.CloudAPI().K8S().Start(ctx, k8s.StartRequest{K8SID: k8sID})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot start cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
}
}
if plan.Enabled.ValueBool() || plan.Enabled.IsNull() {
if !plan.Start.ValueBool() && !plan.Start.IsNull() {
_, err := c.CloudAPI().K8S().Stop(ctx, k8s.StopRequest{K8SID: k8sID})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot stop cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
}
}
tflog.Info(ctx, "Start/Stop cluster successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
func K8SCPDeleteMaster(ctx context.Context, plan *models.ResourceK8SCPModel, state *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Delete Master node from cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
deleteMasterComp := make([]string, 0)
for i, val := range state.DetailedInfo.Elements() {
if i == 2 {
break
}
obj, err := types.ObjectValueFrom(ctx, models.ItemDetailedInfo, val)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDetailedInfo struct to obj", err), map[string]any{"k8s_id": plan.Id.ValueString()})
}
id := obj.Attributes()["compute_id"]
deleteMasterComp = append(deleteMasterComp, id.String())
}
req := k8s.DeleteMasterFromGroupRequest{
K8SID: uint64(state.K8SID.ValueInt64()),
MasterGroupID: uint64(state.MasterGroupId.ValueInt64()),
MasterIDs: deleteMasterComp,
}
_, err := c.CloudAPI().K8S().DeleteMasterFromGroup(ctx, req)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot delete master node from cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
tflog.Info(ctx, "Delete Master node from cluster successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}
func K8CPUpdateSysctlParams(ctx context.Context, plan *models.ResourceK8SCPModel, state *models.ResourceK8SCPModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Update LB parameters from cluster with ID", map[string]any{"k8s_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
result := make([]map[string]interface{}, 0, len(plan.LBSysctlParams.Elements()))
for _, val := range plan.LBSysctlParams.Elements() {
objVal := val.(types.Object)
valMap := objVal.Attributes()
mapKey := valMap["key"].(types.String).ValueString()
mapVal := valMap["value"].(types.String).ValueString()
tempMap := make(map[string]interface{})
tempMap[mapKey] = mapVal
result = append(result, tempMap)
}
req := lb.UpdateSysctParamsRequest{
LBID: uint64(state.LBID.ValueInt64()),
SysctlParams: result,
}
_, err := c.CloudAPI().LB().UpdateSysctlParams(ctx, req)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot update LB parameters from cluster with ID - %s", plan.Id.ValueString()), err.Error())
return diags
}
tflog.Info(ctx, "Update LB parameters from cluster with ID successfully", map[string]any{"k8s_id": plan.Id.ValueString()})
return diags
}

View File

@@ -0,0 +1,220 @@
package utilities
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/k8s/models"
)
func CreateRequestResourceK8WG(ctx context.Context, plan *models.ResourceK8SWGModel) k8s.WorkersGroupAddRequest {
tflog.Info(ctx, "Start CreateRequestResourceK8WG", map[string]any{"name": plan.Name.ValueString()})
req := k8s.WorkersGroupAddRequest{
K8SID: uint64(plan.K8SID.ValueInt64()),
Name: plan.Name.ValueString(),
}
if !plan.WorkerSEPID.IsNull() {
req.WorkerSEPID = uint64(plan.WorkerSEPID.ValueInt64())
} else {
req.WorkerSEPID = 0
}
if !plan.WorkerSEPPool.IsNull() {
req.WorkerSEPPool = plan.WorkerSEPPool.ValueString()
}
if !plan.Num.IsUnknown() {
req.WorkerNum = uint64(plan.Num.ValueInt64())
} else {
req.WorkerNum = 1
}
if !plan.CPU.IsUnknown() {
req.WorkerCPU = uint64(plan.CPU.ValueInt64())
} else {
req.WorkerCPU = 1
}
if !plan.RAM.IsUnknown() {
req.WorkerRAM = uint64(plan.RAM.ValueInt64())
} else {
req.WorkerRAM = 1024
}
if !plan.Disk.IsUnknown() {
req.WorkerDisk = uint64(plan.Disk.ValueInt64())
} else {
req.WorkerDisk = 0
}
if !plan.Annotations.IsUnknown() {
result := make([]string, 0, len(plan.Annotations.Elements()))
for _, val := range plan.Annotations.Elements() {
result = append(result, strings.Trim(val.String(), "\""))
}
req.Annotations = result
}
if !plan.Labels.IsUnknown() {
result := make([]string, 0, len(plan.Labels.Elements()))
for _, val := range plan.Labels.Elements() {
result = append(result, strings.Trim(val.String(), "\""))
}
req.Labels = result
}
if !plan.Taints.IsUnknown() {
result := make([]string, 0, len(plan.Taints.Elements()))
for _, val := range plan.Taints.Elements() {
result = append(result, strings.Trim(val.String(), "\""))
}
req.Taints = result
}
if !plan.CloudInit.IsNull() {
req.UserData = plan.CloudInit.ValueString()
}
tflog.Info(ctx, "End CreateRequestResourceK8WG", map[string]any{"name": plan.Name.ValueString()})
return req
}
func ResourceK8SWGCreate(ctx context.Context, plan *models.ResourceK8SWGModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start ResourceK8SWGCreate", map[string]any{"name": plan.Name.ValueString(), "k8s_id": plan.K8SID.ValueInt64()})
diags := diag.Diagnostics{}
// Make request and get response
wgId, err := c.CloudAPI().K8S().WorkersGroupAdd(ctx, CreateRequestResourceK8WG(ctx, plan))
if err != nil {
tflog.Error(ctx, "Error response for create k8s_wg")
diags.AddError("Unable to Create K8SWG", err.Error())
return diags
}
plan.Id = types.StringValue(strconv.Itoa(int(wgId)))
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
wg, k8sId, err := K8SWGResourceCheckPresence(ctx, plan, c)
if err != nil {
diags.AddError("Cannot get info about wg ", err.Error())
return diags
}
tflog.Info(ctx, "End ResourceK8SWGCreate", map[string]any{"k8s_id": k8sId, "k8s_wg": wg.ID})
return diags
}
func K8SWGResourceCheckPresence(ctx context.Context, plan *models.ResourceK8SWGModel, c *decort.DecortClient) (*k8s.ItemK8SGroup, uint64, error) {
tflog.Info(ctx, "Get info about wg with ID", map[string]any{"wg_id": plan.Id.ValueString()})
var wgId int
var k8sId int
var err error
ids := strings.Split(plan.Id.ValueString(), "#")
if len(ids) == 2 {
k8sId, err = strconv.Atoi(ids[0])
if err != nil {
return nil, 0, err
}
wgId, err = strconv.Atoi(ids[1])
if err != nil {
return nil, 0, err
}
} else {
wgId, err = strconv.Atoi(plan.Id.ValueString())
if err != nil {
return nil, 0, err
}
k8sId = int(plan.K8SID.ValueInt64())
}
cluster, err := c.CloudAPI().K8S().Get(ctx, k8s.GetRequest{K8SID: uint64(k8sId)})
if err != nil {
return nil, 0, fmt.Errorf("cannot get info about cluster with error: %w", err)
}
for _, wg := range cluster.K8SGroups.Workers {
if wg.ID == uint64(wgId) {
tflog.Info(ctx, "Getting info about wg successfully", map[string]any{"wg_id": plan.Id.ValueString()})
return &wg, cluster.ID, nil
}
}
tflog.Error(ctx, fmt.Sprintf("Getting info about wg end with error - %s", err.Error()))
return nil, 0, fmt.Errorf("not found wg with id: %d in k8s cluster: %d", wgId, cluster.ID)
}
func K8SWGUpdateCloudInit(ctx context.Context, plan, state *models.ResourceK8SWGModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Update cloud init in wg with id", map[string]any{"wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
diags := diag.Diagnostics{}
req := k8s.UpdateWorkerNodesMetaDataRequest{
K8SID: uint64(state.K8SID.ValueInt64()),
WorkersGroupID: uint64(state.WorkerGroupId.ValueInt64()),
UserData: plan.CloudInit.ValueString(),
}
_, err := c.CloudAPI().K8S().UpdateWorkerNodesMetaData(ctx, req)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot update cloud init in wg with id: %d", state.WorkerGroupId.ValueInt64()), err.Error())
return diags
}
tflog.Info(ctx, "Update cloud init successfully in wg with id", map[string]any{"wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
return diags
}
func K8SWGUpdateNumWorkers(ctx context.Context, plan, state *models.ResourceK8SWGModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Update num workers in wg with id", map[string]any{"wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
diags := diag.Diagnostics{}
wg, k8sId, err := K8SWGResourceCheckPresence(ctx, plan, c)
if err != nil {
diags.AddError("Cannot get info about wg ", err.Error())
return diags
}
if newNum := plan.Num.ValueInt64(); uint64(newNum) > wg.Num {
req := k8s.WorkerAddRequest{
K8SID: k8sId,
WorkersGroupID: wg.ID,
Num: uint64(newNum) - wg.Num,
}
tflog.Info(ctx, "Add workers in wg with id", map[string]any{"wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
_, err := c.CloudAPI().K8S().WorkerAdd(ctx, req)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot add workers in wg with id: %d", state.WorkerGroupId.ValueInt64()), err.Error())
return diags
}
tflog.Info(ctx, "Add workers successfully in wg with id", map[string]any{"wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
} else {
for i := int64(wg.Num) - 1; i >= newNum; i-- {
req := k8s.DeleteWorkerFromGroupRequest{
K8SID: k8sId,
WorkersGroupID: wg.ID,
WorkerID: wg.DetailedInfo[i].ID,
}
tflog.Info(ctx, "Start delete worker in wg with id", map[string]any{"worker_id": wg.DetailedInfo[i].ID, "wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
_, err := c.CloudAPI().K8S().DeleteWorkerFromGroup(ctx, req)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot delete worker from wg with id: %d", state.WorkerGroupId.ValueInt64()), err.Error())
return diags
}
tflog.Info(ctx, "End delete worker successfully in wg with id", map[string]any{"worker_id": wg.DetailedInfo[i].ID, "wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
}
}
tflog.Info(ctx, "Update num workers successfully in wg with id", map[string]any{"wg_id": state.WorkerGroupId.ValueInt64(), "k8s_id": state.K8SID.ValueInt64()})
return diags
}