routeros

package
v1.48.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 7, 2024 License: MPL-2.0 Imports: 32 Imported by: 2

Documentation

Index

Constants

View Source
const (
	TRACE logLevel = 1 + iota
	DEBUG
	INFO
	WARN
	ERROR
)
View Source
const (
	MetaId             = "___id___"
	MetaResourcePath   = "___path___"
	MetaTransformSet   = "___ts___"
	MetaSkipFields     = "___skip___"
	MetaSetUnsetFields = "___unset___"
	MetaDropByValue    = "___drop_val___"
)

All metadata fields must be present in each resource schema, and the field type must be string.

View Source
const (
	KeyActualMtu               = "actual_mtu"
	KeyAllowFastPath           = "allow_fast_path"
	KeyArp                     = "arp"
	KeyArpTimeout              = "arp_timeout"
	KeyClampTcpMss             = "clamp_tcp_mss"
	KeyComment                 = "comment"
	KeyDynamic                 = "dynamic"
	KeyDisabled                = "disabled"
	KeyDontFragment            = "dont_fragment"
	KeyDscp                    = "dscp"
	KeyFilter                  = "filter"
	KeyInactive                = "inactive"
	KeyInterface               = "interface"
	KeyInvalid                 = "invalid"
	KeyIpsecSecret             = "ipsec_secret"
	KeyKeepalive               = "keepalive"
	KeyL2Mtu                   = "l2mtu"
	KeyLocalAddress            = "local_address"
	KeyLoopProtect             = "loop_protect"
	KeyLoopProtectDisableTime  = "loop_protect_disable_time"
	KeyLoopProtectSendInterval = "loop_protect_send_interval"
	KeyLoopProtectStatus       = "loop_protect_status"
	KeyMacAddress              = "mac_address"
	KeyMtu                     = "mtu"
	KeyName                    = "name"
	KeyPlaceBefore             = "place_before"
	KeyRemoteAddress           = "remote_address"
	KeyRunning                 = "running"
	KeyVrf                     = "vrf"
)
View Source
const KeyLen = 32 // wgh.KeyLen

https://github.com/WireGuard/wgctrl-go/blob/master/wgtypes/types.go KeyLen is the expected key length for a WireGuard key.

View Source
const UniqueIdPrefix = `terraform-`

Copied from terraform-plugin-testing@v1.2.0/helper/resource/id.go Because this functionality is marked deprecated.

Variables

View Source
var (
	ErrorMsgPut    = "An error was encountered while sending a PUT request to the API: %v"
	ErrorMsgGet    = "An error was encountered while sending a GET request to the API: %v"
	ErrorMsgPatch  = "An error was encountered while sending a PATCH request to the API: %v"
	ErrorMsgDelete = "An error was encountered while sending a DELETE request to the API: %v"
)
View Source
var (
	PropActualMtuRo = &schema.Schema{
		Type:     schema.TypeInt,
		Computed: true,
	}
	PropAllowFastPathRw = &schema.Schema{
		Type:             schema.TypeBool,
		Optional:         true,
		Description:      "Whether to allow FastPath processing. Must be disabled if IPsec tunneling is used.",
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropArpRw = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
		Description: `Address Resolution Protocol mode:
		* disabled - the interface will not use ARP
		* enabled - the interface will use ARP
		* local-proxy-arp - the router performs proxy ARP on the interface and sends replies to the same interface
		* proxy-arp - the router performs proxy ARP on the interface and sends replies to other interfaces
		* reply-only - the interface will only reply to requests originated from matching IP address/MAC address combinations which are entered as static entries in the ARP table. No dynamic entries will be automatically stored in the ARP table. Therefore for communications to be successful, a valid static entry must already exist.`,
		ValidateFunc: validation.StringInSlice([]string{"disabled", "enabled", "local-proxy-arp", "proxy-arp",
			"reply-only"}, false),
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropArpTimeoutRw = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
		Description: "ARP timeout is time how long ARP record is kept in ARP table after no packets are received " +
			"from IP. Value auto equals to the value of arp-timeout in IP/Settings, default is 30s. Can use postfix " +
			"ms, s, M, h, d for milliseconds, seconds, minutes, hours or days. If no postfix is set then seconds (s) is used.",
		ValidateFunc: validation.StringMatch(regexp.MustCompile(`^$|auto$|(\d+(ms|s|M|h|d)?)+$`),
			"expected arp_timout value to be 'auto' string or time value"),
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropClampTcpMssRw = &schema.Schema{
		Type:     schema.TypeBool,
		Optional: true,
		Description: "Controls whether to change MSS size for received TCP SYN packets. When enabled, a " +
			"router will change the MSS size for received TCP SYN packets if the current MSS size exceeds the " +
			"tunnel interface MTU (taking into account the TCP/IP overhead). The received encapsulated packet " +
			"will still contain the original MSS, and only after decapsulation the MSS is changed.",
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropCommentRw = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
	}
	PropDisabledRw = &schema.Schema{
		Type:             schema.TypeBool,
		Optional:         true,
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropDontFragmentRw = &schema.Schema{
		Type:             schema.TypeString,
		Optional:         true,
		ValidateFunc:     validation.StringInSlice([]string{"inherit", "no"}, false),
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropDscpRw = &schema.Schema{

		Type:     schema.TypeString,
		Optional: true,
		Default:  "inherit",
		ValidateDiagFunc: func(v interface{}, p cty.Path) (diags diag.Diagnostics) {
			value := v.(string)

			if value == "" || value == "inherit" {
				return
			}

			i, err := strconv.Atoi(value)
			if err != nil {
				diags = diag.Errorf(
					"expected dscp value (%s) to be empty string or 'inherit' or integer 0..63", value)
				return
			}

			if i < 0 || i > 63 {
				diags = diag.Errorf(
					"expected %s to be in the range 0 - 63, got %d", value, i)
				return
			}

			return
		},
		Description: "Set dscp value in GRE header to a fixed value '0..63' or 'inherit' from dscp value taken " +
			"from tunnelled traffic.",
	}
	PropDynamicRo = &schema.Schema{
		Type:     schema.TypeBool,
		Computed: true,
		Description: "Configuration item created by software, not by management interface. It is not exported, " +
			"and cannot be directly modified.",
	}
	PropFilterRw = &schema.Schema{
		Type:        schema.TypeMap,
		Optional:    true,
		Elem:        schema.TypeString,
		Description: "Additional request filtering options.",
	}
	PropInactiveRo = &schema.Schema{
		Type:     schema.TypeBool,
		Computed: true,
	}
	PropInterfaceRw = &schema.Schema{
		Type:        schema.TypeString,
		Required:    true,
		Description: "Name of the interface.",
	}
	PropInvalidRo = &schema.Schema{
		Type:     schema.TypeBool,
		Computed: true,
	}
	PropIpsecSecretRw = &schema.Schema{
		Type:      schema.TypeString,
		Optional:  true,
		Sensitive: true,
		Description: "When secret is specified, router adds dynamic IPsec peer to remote-address with " +
			"pre-shared key and policy (by default phase2 uses sha1/aes128cbc).",
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropKeepaliveRw = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
		Default:  "10s,10",
		ValidateFunc: validation.StringMatch(regexp.MustCompile(`^(\d+[smhdw]?)+(,\d+)?$`),
			"value must be integer[/time],integer 0..4294967295 (https://help.mikrotik.com/docs/display/ROS/GRE)"),
		Description: "Tunnel keepalive parameter sets the time interval in which the tunnel running flag will " +
			"remain even if the remote end of tunnel goes down. If configured time,retries fail, interface " +
			"running flag is removed. Parameters are written in following format: " +
			"KeepaliveInterval,KeepaliveRetries where KeepaliveInterval is time interval and " +
			"KeepaliveRetries - number of retry attempts. KeepaliveInterval is integer 0..4294967295",
		DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
			if old == new {
				return true
			}

			if old == "" || new == "" {
				return false
			}

			o := strings.Split(old, ",")
			n := strings.Split(new, ",")
			if len(o) != 2 || len(n) != 2 {
				panic(fmt.Sprintf("[GRE keepalive] wrong keepalive format, old: '%v', new: '%v'", old, new))
			}

			if o[1] != n[1] {
				return false
			}

			oDuration, err := ParseDuration(o[0])
			if err != nil {
				panic("[GRE keepalive] parse 'old' duration error: " + err.Error())
			}

			nDuration, err := ParseDuration(n[0])
			if err != nil {
				panic("[GRE keepalive] parse 'new' duration error: " + err.Error())
			}

			return oDuration.Seconds() == nDuration.Seconds()
		},
	}
	PropL2MtuRo = &schema.Schema{
		Type:     schema.TypeInt,
		Computed: true,
		Description: "Layer2 Maximum transmission unit. " +
			"[See](https://wiki.mikrotik.com/wiki/Maximum_Transmission_Unit_on_RouterBoards).",
	}
	PropL2MtuRw = &schema.Schema{
		Type:     schema.TypeInt,
		Optional: true,
		Description: "Layer2 Maximum transmission unit. " +
			"[See](https://wiki.mikrotik.com/wiki/Maximum_Transmission_Unit_on_RouterBoards).",
		ValidateFunc:     validation.IntBetween(1, 65535),
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropLocalAddressRw = &schema.Schema{
		Type:             schema.TypeString,
		Optional:         true,
		Description:      "Source address of the tunnel packets, local on the router.",
		ValidateFunc:     validation.IsIPv4Address,
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropLoopProtectRw = &schema.Schema{
		Type:             schema.TypeString,
		Optional:         true,
		ValidateFunc:     validation.StringInSlice([]string{"default", "on", "off"}, false),
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropLoopProtectDisableTimeRw = &schema.Schema{
		Type:             schema.TypeString,
		Optional:         true,
		ValidateFunc:     ValidationTime,
		DiffSuppressFunc: TimeEquall,
	}
	PropLoopProtectSendIntervalRw = &schema.Schema{
		Type:             schema.TypeString,
		Optional:         true,
		ValidateFunc:     ValidationTime,
		DiffSuppressFunc: TimeEquall,
	}
	PropLoopProtectStatusRo = &schema.Schema{
		Type:     schema.TypeString,
		Computed: true,
	}
	PropMacAddressRo = &schema.Schema{
		Type:        schema.TypeString,
		Computed:    true,
		Description: "Current mac address.",
	}
	// TODO: Replace in all possible resources with a property without 'ForceNew'.
	// https://github.com/orgs/terraform-routeros/discussions/192#discussioncomment-5929999
	PropNameForceNewRw = &schema.Schema{
		Type:     schema.TypeString,
		Required: true,
		ForceNew: true,
		Description: `Changing the name of this resource will force it to be recreated.
	> The links of other configuration properties to this resource may be lost!
	> Changing the name of the resource outside of a Terraform will result in a loss of control integrity for that resource!
`,
	}
	PropPlaceBefore = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
		ForceNew: true,
		Description: `Before which position the rule will be inserted.  
	> Please check the effect of this option, as it does not work as you think!  
	> Best way to use in conjunction with a data source. See [example](../data-sources/firewall.md#example-usage).  
`,
	}
	PropRemoteAddressRw = &schema.Schema{
		Type:             schema.TypeString,
		Optional:         true,
		Description:      "IP address of the remote end of the tunnel.",
		ValidateFunc:     validation.IsIPv4Address,
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
	PropRunningRo = &schema.Schema{
		Type:     schema.TypeBool,
		Computed: true,
	}
	PropVrfRw = &schema.Schema{
		Type:             schema.TypeString,
		Optional:         true,
		Description:      "The VRF table this resource operates on.",
		DiffSuppressFunc: AlwaysPresentNotUserProvided,
	}
)

Schema properties.

View Source
var (
	ValidationTime = validation.StringMatch(regexp.MustCompile(`^(\d+([smhdw]|ms)?)+$`),
		"value should be an integer or a time interval: 0..4294967295 (seconds) or 500ms, 2d, 1w")

	// ValidationDurationAtLeast returns a SchemaValidateDiagFunc which tests if the provided value
	// is a valid duration expected by RouterOS and is at least minDuration long (inclusive)
	ValidationDurationAtLeast = func(minDuration time.Duration) schema.SchemaValidateDiagFunc {
		return func(i interface{}, p cty.Path) diag.Diagnostics {
			value, ok := i.(string)
			if !ok {
				return diag.Errorf("expected type to be string")
			}

			duration, err := ParseDuration(value)
			if err != nil {
				return diag.FromErr(err)
			}

			if duration < minDuration {
				return diag.Errorf("duration must be greater than %v", minDuration)
			}

			return diag.Diagnostics{}
		}
	}

	ValidationAutoYesNo = validation.StringInSlice([]string{"auto", "yes", "no"}, false)
	ValidationIpAddress = validation.StringMatch(
		regexp.MustCompile(`^$|^!?(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/([0-9]|[0-9]|[1-2][0-9]|3[0-2]))?)$`),
		"Allowed addresses should be a CIDR IP address or an empty string",
	)
	ValidationMacAddress = validation.StringMatch(
		regexp.MustCompile(`^!?\b(?:[0-9A-F]{2}\:){5}(?:[0-9A-F]{2})$`),
		"Allowed MAC addresses should be [!]AA:BB:CC:DD:EE:FF",
	)

	// ValidationMultiValInSlice returns a SchemaValidateDiagFunc which works like the StringInSlice function,
	// but the provided value can be a single value or a comma-separated list of values.
	// The negative indication of the parameter is also supported by adding "!" before value if mikrotikNegative is true.
	ValidationMultiValInSlice = func(valid []string, ignoreCase, mikrotikNegative bool) schema.SchemaValidateDiagFunc {
		return func(i interface{}, path cty.Path) (diags diag.Diagnostics) {
			v, ok := i.(string)

			if !ok {
				diags = append(diags, diag.Diagnostic{
					Severity: diag.Error,
					Summary:  "Bad value type",
					Detail:   fmt.Sprintf("Value should be a string: %v (type = %T)", v, v),
				})

				return
			}

			var negative []string
			if mikrotikNegative {
				for _, str := range valid {
					negative = append(negative, "!"+str)
				}
			}

			for _, sValue := range strings.Split(v, ",") {
				ok := false
				sValue = strings.TrimSpace(sValue)

				for _, sValid := range append(negative, valid...) {
					if sValue == sValid || (ignoreCase && strings.EqualFold(sValue, sValid)) {
						ok = true
						break
					}
				}

				if !ok {
					diags = append(diags, diag.Diagnostic{
						Severity: diag.Error,
						Summary:  "Bad value",
						Detail:   fmt.Sprintf("Unexpected value: %v", sValue),
					})
				}
			}

			return
		}
	}

	ValidationValInSlice = func(valid []string, ignoreCase, mikrotikNegative bool) schema.SchemaValidateDiagFunc {
		return func(i interface{}, path cty.Path) (diags diag.Diagnostics) {
			v, ok := i.(string)

			if !ok {
				diags = append(diags, diag.Diagnostic{
					Severity: diag.Error,
					Summary:  "Bad value type",
					Detail:   fmt.Sprintf("Value should be a string: %v (type = %T)", v, v),
				})

				return
			}

			var negative []string
			if mikrotikNegative {
				for _, str := range valid {
					negative = append(negative, "!"+str)
				}
			}

			v = strings.TrimSpace(v)

			for _, str := range append(negative, valid...) {
				if v == str || (ignoreCase && strings.EqualFold(v, str)) {
					return
				}
			}

			diags = append(diags, diag.Diagnostic{
				Severity: diag.Error,
				Summary:  "Bad value",
				Detail:   fmt.Sprintf("Unexpected value: %v", v),
			})

			return
		}
	}
)

Properties validation.

View Source
var (
	TimeEquall = func(k, old, new string, d *schema.ResourceData) bool {
		if old == "" {
			return false
		}

		if AlwaysPresentNotUserProvided(k, old, new, d) {
			return true
		}

		oDuration, err := ParseDuration(old)
		if err != nil {
			panic("[TimeEquall] parse 'old' duration error: " + err.Error())
		}

		nDuration, err := ParseDuration(new)
		if err != nil {
			panic("[TimeEquall] parse 'new' duration error: " + err.Error())
		}

		return oDuration.Seconds() == nDuration.Seconds()
	}

	HexEqual = func(k, old, new string, d *schema.ResourceData) bool {
		if old == "" {
			return false
		}

		if AlwaysPresentNotUserProvided(k, old, new, d) {
			return true
		}

		// Compare numbers:
		var iOld, iNew int64
		var err error

		iOld, err = strconv.ParseInt(old, 0, 64)
		if err != nil {
			panic("[HexEqual] 'old' number parse error: " + err.Error())
		}

		iNew, err = strconv.ParseInt(new, 0, 64)
		if err != nil {
			panic("[HexEqual] 'new' number parse error: " + err.Error())
		}

		return iOld == iNew
	}

	// AlwaysPresentNotUserProvided is a SupressDiff function that prevents values not provided by users to get updated.
	// This is necessary in some system-wide fields that are present regardless if the users provides any values.
	// Prevents the need of hardcode values for default values, as those are harder to track over time/versions of
	// routeros
	AlwaysPresentNotUserProvided = func(k, old, new string, d *schema.ResourceData) bool {
		if old == "" {
			return false
		}

		value := d.GetRawConfig()

	loop:
		for _, key := range strings.Split(k, ".") {
			if key == "#" || key == "%" {
				break
			}

			switch {
			case value.Type().IsObjectType():
				value = value.GetAttr(key)
			case value.Type().IsMapType():
				value = value.Index(cty.StringVal(key))

			default:
				break loop
			}

			if value.IsNull() {
				return true
			}
		}

		return false
	}

	MacAddressEqual = func(k, old, new string, d *schema.ResourceData) bool {
		return strings.EqualFold(old, new)
	}
)

Properties DiffSuppressFunc.

View Source
var DeleteSystemObject = []diag.Diagnostic{{
	Severity: diag.Warning,
	Summary:  "Delete operation on a system object.",
	Detail: "This resource contains system settings and cannot be deleted or reset. " +
		"This action will remove the object from the Terraform state. " +
		"See also: 'terraform state rm' https://developer.hashicorp.com/terraform/cli/commands/state/rm",
}}

Diagnostics

Functions

func BoolFromMikrotikJSON

func BoolFromMikrotikJSON(s string) bool

func BoolFromMikrotikJSONStr added in v1.7.0

func BoolFromMikrotikJSONStr(s string) string

func BoolToMikrotikJSON

func BoolToMikrotikJSON(b bool) string

func BoolToMikrotikJSONStr added in v1.7.0

func BoolToMikrotikJSONStr(s string) string

func ColorizedDebug

func ColorizedDebug(ctx context.Context, msg string, args ...map[string]interface{})

ColorizedDebug Used to display provider log color messages. Please set the environment variable

func ColorizedMessage added in v1.21.0

func ColorizedMessage(ctx context.Context, level logLevel, msg string, args ...map[string]interface{})

func DatasourceFiles added in v1.45.0

func DatasourceFiles() *schema.Resource

func DatasourceFirewall

func DatasourceFirewall() *schema.Resource

func DatasourceIPAddresses

func DatasourceIPAddresses() *schema.Resource

func DatasourceIPRoutes

func DatasourceIPRoutes() *schema.Resource

func DatasourceIPServices added in v1.39.0

func DatasourceIPServices() *schema.Resource

func DatasourceIPv6Addresses

func DatasourceIPv6Addresses() *schema.Resource

func DatasourceInterfaces

func DatasourceInterfaces() *schema.Resource

func DatasourceIpArp added in v1.24.0

func DatasourceIpArp() *schema.Resource

func DatasourceIpDhcpServerLeases added in v1.28.0

func DatasourceIpDhcpServerLeases() *schema.Resource

func DatasourceSystemResource added in v1.24.0

func DatasourceSystemResource() *schema.Resource

func DefaultCreate

func DefaultCreate(s map[string]*schema.Schema) schema.CreateContextFunc

func DefaultDelete

func DefaultDelete(s map[string]*schema.Schema) schema.DeleteContextFunc

func DefaultRead

func DefaultRead(s map[string]*schema.Schema) schema.ReadContextFunc

func DefaultSystemCreate

func DefaultSystemCreate(s map[string]*schema.Schema) schema.CreateContextFunc

func DefaultSystemDatasourceRead added in v1.24.0

func DefaultSystemDatasourceRead(s map[string]*schema.Schema) schema.ReadContextFunc

func DefaultSystemDelete

func DefaultSystemDelete(s map[string]*schema.Schema) schema.DeleteContextFunc

func DefaultSystemRead

func DefaultSystemRead(s map[string]*schema.Schema) schema.ReadContextFunc

func DefaultSystemUpdate

func DefaultSystemUpdate(s map[string]*schema.Schema) schema.UpdateContextFunc

func DefaultUpdate

func DefaultUpdate(s map[string]*schema.Schema) schema.UpdateContextFunc

func DeleteItem

func DeleteItem(id *ItemId, resourcePath string, c Client) error

func ImportStateCustomContext added in v1.44.3

func ImportStateCustomContext(s map[string]*schema.Schema) schema.StateContextFunc

ImportStateCustomContext is an implementation of StateContextFunc that can be used to import resources with the ability to explicitly or implicitly specify a key field. `terraform [global options] import [options] ADDR ID`. During import the content of the `ID` is checked and depending on the specified string it is possible to automatically search for the internal Mikrotik identifier. Logic of `ID` processing - The first character of the string contains an asterisk (standard Mikrotik identifier `*3E`): import without additional search. - String containing no "=" character (`wifi-01`): the "name" field is used for searching. - String containing only one "=" character (`"comment=hAP-ac3"`): the "word left" and "word right" pair is used for searching.

func IpRangeToCIDR

func IpRangeToCIDR(ip1, ip2 string) (string, error)

func KebabToSnake

func KebabToSnake(name string) string

KebabToSnake Convert Mikrotik JSON names to TF schema names: some-filed to some_field.

func ListToString

func ListToString(v any) (res string)

ListToString Convert List and Set to a delimited string.

func MikrotikResourceDataToTerraform

func MikrotikResourceDataToTerraform(item MikrotikItem, s map[string]*schema.Schema, d *schema.ResourceData) diag.Diagnostics

MikrotikResourceDataToTerraform Unmarshal Mikrotik resource (incoming data: JSON, etc.) to TF resource schema.

func MikrotikResourceDataToTerraformDatasource

func MikrotikResourceDataToTerraformDatasource(items *[]MikrotikItem, resourceDataKeyName string, s map[string]*schema.Schema, d *schema.ResourceData) diag.Diagnostics

func NewClient

func NewClient(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics)

func NewProvider

func NewProvider() *schema.Provider

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

func PrefixedUniqueId

func PrefixedUniqueId(prefix string) string

func PropDropByValue added in v1.35.0

func PropDropByValue(s ...string) *schema.Schema

func PropId

func PropId(t IdType) *schema.Schema

PropId Resource ID property.

func PropMacAddressRw added in v1.32.0

func PropMacAddressRw(description string, required bool) *schema.Schema

PropMacAddress

func PropMtuRw

func PropMtuRw() *schema.Schema

PropMtuRw MTU value can be integer or 'auto'.

func PropName added in v1.5.0

func PropName(description string) *schema.Schema

PropName

func PropResourcePath

func PropResourcePath(p string) *schema.Schema

PropResourcePath Resource path property.

func PropSetUnsetFields added in v1.20.1

func PropSetUnsetFields(s ...string) *schema.Schema

PropSetUnsetFields

func PropSkipFields added in v1.3.0

func PropSkipFields(s ...string) *schema.Schema

PropSkipFields

func PropTransformSet

func PropTransformSet(s ...string) *schema.Schema

PropTransformSet

func Provider

func Provider() *schema.Provider

func ReadItems

func ReadItems(id *ItemId, resourcePath string, c Client) (*[]MikrotikItem, error)

func ReadItemsFiltered

func ReadItemsFiltered(filter []string, resourcePath string, c Client) (*[]MikrotikItem, error)

func ResourceCapsManAccessList added in v1.19.0

func ResourceCapsManAccessList() *schema.Resource

https://help.mikrotik.com/docs/display/ROS/CAPsMAN

func ResourceCapsManChannelV0 added in v1.21.0

func ResourceCapsManChannelV0() *schema.Resource

func ResourceCapsManConfigurationV0 added in v1.21.0

func ResourceCapsManConfigurationV0() *schema.Resource

func ResourceCapsManDatapathV0 added in v1.21.0

func ResourceCapsManDatapathV0() *schema.Resource

func ResourceCapsManInterface added in v1.44.0

func ResourceCapsManInterface() *schema.Resource

https://help.mikrotik.com/docs/display/ROS/CAPsMAN

func ResourceCapsManRatesV0 added in v1.21.0

func ResourceCapsManRatesV0() *schema.Resource

func ResourceCapsManSecurityV0 added in v1.21.0

func ResourceCapsManSecurityV0() *schema.Resource

func ResourceCertificateScepServer added in v1.46.0

func ResourceCertificateScepServer() *schema.Resource

func ResourceCreate

func ResourceCreate(ctx context.Context, s map[string]*schema.Schema, d *schema.ResourceData, m interface{}) diag.Diagnostics

ResourceCreate Creation of a resource in accordance with the TF Schema.

func ResourceDelete

func ResourceDelete(ctx context.Context, s map[string]*schema.Schema, d *schema.ResourceData, m interface{}) diag.Diagnostics

ResourceDelete Deleting the resource.

func ResourceDhcpClientOption added in v1.33.0

func ResourceDhcpClientOption() *schema.Resource

ResourceDhcpClient https://help.mikrotik.com/docs/display/ROS/DHCP#DHCP-DHCPClient

func ResourceDhcpRelay added in v1.45.0

func ResourceDhcpRelay() *schema.Resource

ResourceDhcpRelay https://wiki.mikrotik.com/wiki/Manual:IP/DHCP_Relay

func ResourceDhcpServerConfig added in v1.22.0

func ResourceDhcpServerConfig() *schema.Resource

ResourceDhcpServerConfig https://help.mikrotik.com/docs/display/ROS/DHCP#DHCP-StoreConfiguration

func ResourceDhcpServerLease

func ResourceDhcpServerLease() *schema.Resource

ResourceDhcpServerLease https://wiki.mikrotik.com/wiki/Manual:IP/DHCP_Server

func ResourceDhcpServerNetwork

func ResourceDhcpServerNetwork() *schema.Resource

ResourceDhcpServerNetwork https://wiki.mikrotik.com/wiki/Manual:IP/DHCP_Server#Networks

func ResourceDhcpServerOption added in v1.15.0

func ResourceDhcpServerOption() *schema.Resource

ResourceDhcpServerOption https://help.mikrotik.com/docs/display/ROS/DHCP#DHCP-DHCPServer

func ResourceDhcpServerOptionSet added in v1.15.0

func ResourceDhcpServerOptionSet() *schema.Resource

ResourceDhcpServerOption https://wiki.mikrotik.com/wiki/Manual:IP/DHCP_Server

func ResourceDhcpServerV0 added in v1.21.0

func ResourceDhcpServerV0() *schema.Resource

func ResourceIPAddress

func ResourceIPAddress() *schema.Resource

ResourceIPAddress https://wiki.mikrotik.com/wiki/Manual:IP/Address

func ResourceIPConnectionTracking added in v1.17.0

func ResourceIPConnectionTracking() *schema.Resource

ResourceIPConnectionTracking https://help.mikrotik.com/docs/display/ROS/Connection+tracking

func ResourceIPFirewallAddrList

func ResourceIPFirewallAddrList() *schema.Resource

ResourceIPFirewallAddrList https://wiki.mikrotik.com/wiki/Manual:IP/Firewall/Address_list

func ResourceIPFirewallFilter

func ResourceIPFirewallFilter() *schema.Resource

ResourceIPFirewallFilter https://wiki.mikrotik.com/wiki/Manual:IP/Firewall/Filter

func ResourceIPFirewallMangle

func ResourceIPFirewallMangle() *schema.Resource

ResourceIPFirewallMangle https://wiki.mikrotik.com/wiki/Manual:IP/Firewall/Mangle

func ResourceIPFirewallNat

func ResourceIPFirewallNat() *schema.Resource

ResourceIPFirewallNat https://wiki.mikrotik.com/wiki/Manual:IP/Firewall/NAT

func ResourceIPPoolV0 added in v1.21.0

func ResourceIPPoolV0() *schema.Resource

func ResourceIPVrf added in v1.48.0

func ResourceIPVrf() *schema.Resource

ResourceIPRoute https://wiki.mikrotik.com/wiki/Manual:Virtual_Routing_and_Forwarding

func ResourceIPv6Address

func ResourceIPv6Address() *schema.Resource

ResourceIPv6Address https://wiki.mikrotik.com/wiki/Manual:IPv6/Address

func ResourceIPv6DhcpClient added in v1.33.0

func ResourceIPv6DhcpClient() *schema.Resource

ResourceIPv6DhcpClient https://help.mikrotik.com/docs/display/ROS/DHCP#DHCP-DHCPv6Client

func ResourceIPv6DhcpClientOption added in v1.34.0

func ResourceIPv6DhcpClientOption() *schema.Resource

ResourceDhcpClient https://help.mikrotik.com/docs/display/ROS/DHCP#DHCP-DHCPClient

func ResourceIPv6FirewallAddrList added in v1.9.0

func ResourceIPv6FirewallAddrList() *schema.Resource

ResourceIPv6FirewallAddrList https://help.mikrotik.com/docs/display/ROS/Address-lists They work more or less the same as IPv4 address lists, except no ranges

func ResourceIPv6NeighborDiscovery added in v1.35.0

func ResourceIPv6NeighborDiscovery() *schema.Resource

ResourceIPv6NeighborDiscovery https://help.mikrotik.com/docs/display/ROS/IPv6+Neighbor+Discovery

func ResourceInterfaceBridge

func ResourceInterfaceBridge() *schema.Resource

ResourceInterfaceBridge https://wiki.mikrotik.com/wiki/Manual:Interface/Bridge

func ResourceInterfaceBridgePort

func ResourceInterfaceBridgePort() *schema.Resource

ResourceInterfaceBridgePort https://wiki.mikrotik.com/wiki/Manual:Interface/Bridge#Port_Settings

func ResourceInterfaceBridgeV0 added in v1.21.0

func ResourceInterfaceBridgeV0() *schema.Resource

func ResourceInterfaceEoip added in v1.20.0

func ResourceInterfaceEoip() *schema.Resource

https://help.mikrotik.com/docs/display/ROS/EoIP

func ResourceInterfaceEoipV0 added in v1.21.0

func ResourceInterfaceEoipV0() *schema.Resource

func ResourceInterfaceEthernet added in v1.14.0

func ResourceInterfaceEthernet() *schema.Resource

ResourceInterfaceEthernet is the schema for ethernet interfaces https://help.mikrotik.com/docs/display/ROS/Ethernet#Ethernet-Properties

func ResourceInterfaceGre

func ResourceInterfaceGre() *schema.Resource

ResourceInterfaceGre https://wiki.mikrotik.com/wiki/Manual:Interface/Gre

func ResourceInterfaceGreV0 added in v1.21.0

func ResourceInterfaceGreV0() *schema.Resource

func ResourceInterfaceIPIP added in v1.32.6

func ResourceInterfaceIPIP() *schema.Resource

ResourceInterfaceIPIP https://wiki.mikrotik.com/wiki/Manual:Interface/IPIP

func ResourceInterfaceList

func ResourceInterfaceList() *schema.Resource

func ResourceInterfaceListMember

func ResourceInterfaceListMember() *schema.Resource

func ResourceInterfaceListV0 added in v1.21.0

func ResourceInterfaceListV0() *schema.Resource

func ResourceInterfaceMacVlan added in v1.38.0

func ResourceInterfaceMacVlan() *schema.Resource

ResourceInterfaceMacVlan https://help.mikrotik.com/docs/display/ROS/MACVLAN

func ResourceInterfaceOpenVPNServer added in v1.5.0

func ResourceInterfaceOpenVPNServer() *schema.Resource

https://help.mikrotik.com/docs/display/ROS/???

func ResourceInterfaceVlan

func ResourceInterfaceVlan() *schema.Resource

ResourceInterfaceVlan https://wiki.mikrotik.com/wiki/Manual:Interface/VLAN

func ResourceInterfaceVlanV0 added in v1.21.0

func ResourceInterfaceVlanV0() *schema.Resource

func ResourceInterfaceVrrp

func ResourceInterfaceVrrp() *schema.Resource

ResourceInterfaceVrrp https://help.mikrotik.com/docs/display/ROS/VRRP

func ResourceInterfaceVrrpV0 added in v1.21.0

func ResourceInterfaceVrrpV0() *schema.Resource

func ResourceInterfaceWireguard

func ResourceInterfaceWireguard() *schema.Resource

ResourceInterfaceWireguard https://help.mikrotik.com/docs/display/ROS/WireGuard

func ResourceInterfaceWireguardPeer

func ResourceInterfaceWireguardPeer() *schema.Resource

ResourceInterfaceWireguardPeer https://help.mikrotik.com/docs/display/ROS/WireGuard#WireGuard-Peers

func ResourceInterfaceWireguardV0 added in v1.21.0

func ResourceInterfaceWireguardV0() *schema.Resource

func ResourceIpNeighborDiscoverySettings added in v1.43.0

func ResourceIpNeighborDiscoverySettings() *schema.Resource

https://help.mikrotik.com/docs/display/ROS/MAC+server

func ResourceMoveItems added in v1.27.2

func ResourceMoveItems() *schema.Resource

func ResourceRead

func ResourceRead(ctx context.Context, s map[string]*schema.Schema, d *schema.ResourceData, m interface{}) diag.Diagnostics

ResourceRead Reading some information about one specific resource.

func ResourceRoutingBGPTemplate added in v1.7.1

func ResourceRoutingBGPTemplate() *schema.Resource

https://help.mikrotik.com/docs/display/ROS/

func ResourceRoutingOspfArea added in v1.11.0

func ResourceRoutingOspfArea() *schema.Resource

ResourceRoutingOspfArea https://help.mikrotik.com/docs/display/ROS/OSPF

func ResourceRoutingOspfInstance added in v1.11.0

func ResourceRoutingOspfInstance() *schema.Resource

ResourceRoutingOspfInstance https://help.mikrotik.com/docs/display/ROS/OSPF

func ResourceRoutingOspfInterfaceTemplate added in v1.11.0

func ResourceRoutingOspfInterfaceTemplate() *schema.Resource

ResourceRoutingOspfInterfaceTemplate https://help.mikrotik.com/docs/display/ROS/OSPF

func ResourceSystemIdentity

func ResourceSystemIdentity() *schema.Resource

func ResourceSystemLogging added in v1.16.0

func ResourceSystemLogging() *schema.Resource

ResourceSystemLogging defines the resource for configuring logging rules https://wiki.mikrotik.com/wiki/Manual:System/Log

func ResourceSystemSchedulerV0 added in v1.21.0

func ResourceSystemSchedulerV0() *schema.Resource

func ResourceSystemScript added in v1.36.0

func ResourceSystemScript() *schema.Resource

ResourceSystemScript https://help.mikrotik.com/docs/display/ROS/Scripting#Scripting-Scriptrepository

func ResourceToolMacServerWinBox added in v1.43.0

func ResourceToolMacServerWinBox() *schema.Resource

https://help.mikrotik.com/docs/display/ROS/MAC+server

func ResourceUPNPInterfaces added in v1.45.0

func ResourceUPNPInterfaces() *schema.Resource

ResourceUPNPInterfaces https://help.mikrotik.com/docs/display/ROS/UPnP

func ResourceUPNPSettings added in v1.45.0

func ResourceUPNPSettings() *schema.Resource

ResourceUPNPSettings https://help.mikrotik.com/docs/display/ROS/UPnP

func ResourceUpdate

func ResourceUpdate(ctx context.Context, s map[string]*schema.Schema, d *schema.ResourceData, m interface{}) diag.Diagnostics

ResourceUpdate Updating the resource in accordance with the TF Schema.

func ResourceWireguardKeys added in v1.18.1

func ResourceWireguardKeys() *schema.Resource

func SnakeToKebab

func SnakeToKebab(name string) string

SnakeToKebab Convert IF schema names to Mikrotik JSON names: some_filed to some-field.

func SystemResourceCreateUpdate

func SystemResourceCreateUpdate(ctx context.Context, s map[string]*schema.Schema, d *schema.ResourceData, m interface{}) diag.Diagnostics

SystemResourceCreateUpdate A resource cannot be created, it can only be changed.

func SystemResourceDelete

func SystemResourceDelete(ctx context.Context, s map[string]*schema.Schema, d *schema.ResourceData, m interface{}) diag.Diagnostics

SystemResourceDelete Delete function will remove the object from the Terraform state No delete functionality provided by API for System Resources.

func SystemResourceRead

func SystemResourceRead(ctx context.Context, s map[string]*schema.Schema, d *schema.ResourceData, m interface{}) diag.Diagnostics

SystemResourceRead The difference from the normal reading is in the method of generation of Id.

func TerraformResourceDataToMikrotik

func TerraformResourceDataToMikrotik(s map[string]*schema.Schema, d *schema.ResourceData) (MikrotikItem, *MikrotikItemMetadata)

TerraformResourceDataToMikrotik Marshal Mikrotik resource from TF resource schema.

func UniqueId

func UniqueId() string

Types

type ApiClient

type ApiClient struct {
	HostURL   string
	Username  string
	Password  string
	Transport TransportType
	*routeros.Client
	// contains filtered or unexported fields
}

func (*ApiClient) GetTransport

func (c *ApiClient) GetTransport() TransportType

func (*ApiClient) SendRequest

func (c *ApiClient) SendRequest(method crudMethod, url *URL, item MikrotikItem, result interface{}) error

type Client

type Client interface {
	GetTransport() TransportType
	SendRequest(method crudMethod, url *URL, item MikrotikItem, result interface{}) error
}

type DataValidateFunc

type DataValidateFunc func(d *schema.ResourceData) diag.Diagnostics

type IdType

type IdType int
const (
	Id IdType = 1 + iota
	Name
)

func (IdType) String

func (t IdType) String() string

type ItemId

type ItemId struct {
	Type  IdType
	Value string
}

type Key added in v1.18.0

type Key [KeyLen]byte

A Key is a public, private, or pre-shared secret key. The Key constructor functions in this package can be used to create Keys suitable for each of these applications.

func GenerateKey added in v1.18.0

func GenerateKey() (Key, error)

GenerateKey generates a Key suitable for use as a pre-shared secret key from a cryptographically safe source.

The output Key should not be used as a private key; use GeneratePrivateKey instead.

func GeneratePrivateKey added in v1.18.0

func GeneratePrivateKey() (Key, error)

GeneratePrivateKey generates a Key suitable for use as a private key from a cryptographically safe source.

func NewKey added in v1.18.0

func NewKey(b []byte) (Key, error)

NewKey creates a Key from an existing byte slice. The byte slice must be exactly 32 bytes in length.

func (Key) PublicKey added in v1.18.0

func (k Key) PublicKey() Key

PublicKey computes a public key from the private key k.

PublicKey should only be called when k is a private key.

func (Key) String added in v1.18.0

func (k Key) String() string

String returns the base64-encoded string representation of a Key.

ParseKey can be used to produce a new Key from this string.

type MikrotikItem

type MikrotikItem map[string]string

MikrotikItem Contains only data.

func CreateItem

func CreateItem(item MikrotikItem, resourcePath string, c Client) (MikrotikItem, error)

func UpdateItem

func UpdateItem(id *ItemId, resourcePath string, item MikrotikItem, c Client) (MikrotikItem, error)

func (MikrotikItem) GetID

func (m MikrotikItem) GetID(t IdType) string

type MikrotikItemMetadata

type MikrotikItemMetadata struct {
	IdType IdType            // The field contains ID.
	Path   string            // Resource URL.
	Meta   map[string]string // Additional metadata that may be present in the schema.
}

MikrotikItemMetadata This information must travel from the schema to the resource polling function.

func GetMetadata

func GetMetadata(s map[string]*schema.Schema) *MikrotikItemMetadata

GetMetadata Get item metadata fields from resource schema.

type RestClient

type RestClient struct {
	HostURL   string
	Username  string
	Password  string
	Transport TransportType
	*http.Client
	// contains filtered or unexported fields
}

func (*RestClient) GetTransport

func (c *RestClient) GetTransport() TransportType

func (*RestClient) SendRequest

func (c *RestClient) SendRequest(method crudMethod, url *URL, item MikrotikItem, result interface{}) error

type TransportType

type TransportType int
const (
	TransportAPI TransportType = 1 + iota
	TransportREST
)

Using numbering from 1 to control type values.

type URL

type URL struct {
	Path  string   // URL path without '/rest'.
	Query []string // Query values.
}

func (*URL) GetApiCmd

func (u *URL) GetApiCmd() []string

GetApiCmd Returns the set of commands for the API client.

func (*URL) GetRestURL

func (u *URL) GetRestURL() string

GetRestURL Returns the URL for the client

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL