-
Notifications
You must be signed in to change notification settings - Fork 455
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
New resource: vsphere_host_port_group #139
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
package vsphere | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/hashicorp/terraform/helper/schema" | ||
"github.com/hashicorp/terraform/helper/validation" | ||
"github.com/hashicorp/terraform/terraform" | ||
"github.com/vmware/govmomi/vim25/types" | ||
) | ||
|
||
const hostPortGroupIDPrefix = "tf-HostPortGroup" | ||
|
||
// schemaHostPortGroupSpec returns schema items for resources that | ||
// need to work with HostPortGroupSpec, such as port groups. | ||
func schemaHostPortGroupSpec() map[string]*schema.Schema { | ||
s := map[string]*schema.Schema{ | ||
// HostPortGroupSpec | ||
"name": &schema.Schema{ | ||
Type: schema.TypeString, | ||
Required: true, | ||
Description: "The name of the port group.", | ||
ForceNew: true, | ||
}, | ||
"vlan_id": &schema.Schema{ | ||
Type: schema.TypeInt, | ||
Optional: true, | ||
Description: "The VLAN ID/trunk mode for this port group. An ID of 0 denotes no tagging, an ID of 1-4094 tags with the specific ID, and an ID of 4095 enables trunk mode, allowing the guest to manage its own tagging.", | ||
Default: 0, | ||
ValidateFunc: validation.IntBetween(0, 4095), | ||
}, | ||
"virtual_switch_name": &schema.Schema{ | ||
Type: schema.TypeString, | ||
Required: true, | ||
Description: "The name of the virtual switch to bind this port group to.", | ||
ForceNew: true, | ||
}, | ||
} | ||
mergeSchema(s, schemaHostNetworkPolicy()) | ||
return s | ||
} | ||
|
||
// expandHostPortGroupSpec reads certain ResourceData keys and returns a | ||
// HostPortGroupSpec. | ||
func expandHostPortGroupSpec(d *schema.ResourceData) *types.HostPortGroupSpec { | ||
obj := &types.HostPortGroupSpec{ | ||
Name: d.Get("name").(string), | ||
VlanId: int32(d.Get("vlan_id").(int)), | ||
VswitchName: d.Get("virtual_switch_name").(string), | ||
Policy: *expandHostNetworkPolicy(d), | ||
} | ||
return obj | ||
} | ||
|
||
// flattenHostPortGroupSpec reads various fields from a HostPortGroupSpec into | ||
// the passed in ResourceData. | ||
func flattenHostPortGroupSpec(d *schema.ResourceData, obj *types.HostPortGroupSpec) error { | ||
d.Set("vlan_id", obj.VlanId) | ||
if err := flattenHostNetworkPolicy(d, &obj.Policy); err != nil { | ||
return err | ||
} | ||
return nil | ||
} | ||
|
||
// calculateComputedPolicy is a utility function to compute a map of state | ||
// attributes for the port group's effective policy. It uses a bit of a | ||
// roundabout way to set the attributes, but allows us to utilize our | ||
// functional deep reading helpers to perform this task, versus having to | ||
// re-write code. | ||
// | ||
// This function relies a bit on some of the lower-level utility functionality | ||
// of helper/schema, so it may need to change in the future. | ||
func calculateComputedPolicy(policy types.HostNetworkPolicy) (map[string]string, error) { | ||
cpr := &schema.Resource{Schema: schemaHostNetworkPolicy()} | ||
cpd := cpr.Data(&terraform.InstanceState{}) | ||
cpd.SetId("effectivepolicy") | ||
if err := flattenHostNetworkPolicy(cpd, &policy); err != nil { | ||
return nil, fmt.Errorf("error setting effective policy data: %s", err) | ||
} | ||
cpm := cpd.State().Attributes | ||
delete(cpm, "id") | ||
return cpm, nil | ||
} | ||
|
||
// calculatePorts is a utility function that returns a set of port data. | ||
func calculatePorts(ports []types.HostPortGroupPort) *schema.Set { | ||
s := make([]interface{}, 0) | ||
for _, port := range ports { | ||
m := make(map[string]interface{}) | ||
m["key"] = port.Key | ||
m["mac_addresses"] = sliceStringsToInterfaces(port.Mac) | ||
m["type"] = port.Type | ||
s = append(s, m) | ||
} | ||
return schema.NewSet(schema.HashResource(portGroupPortSchema()), s) | ||
} | ||
|
||
// portGroupPortSchema returns a sub-schema for a port group's connected ports. | ||
func portGroupPortSchema() *schema.Resource { | ||
return &schema.Resource{ | ||
Schema: map[string]*schema.Schema{ | ||
"key": &schema.Schema{ | ||
Type: schema.TypeString, | ||
Description: "The linkable identifier for this port entry.", | ||
Computed: true, | ||
}, | ||
"mac_addresses": &schema.Schema{ | ||
Type: schema.TypeList, | ||
Description: "The MAC addresses of the network service of the virtual machine connected on this port.", | ||
Computed: true, | ||
Elem: &schema.Schema{Type: schema.TypeString}, | ||
}, | ||
"type": &schema.Schema{ | ||
Type: schema.TypeString, | ||
Description: "Type type of the entity connected on this port. Possible values are host (VMKkernel), systemManagement (service console), virtualMachine, or unknown.", | ||
Computed: true, | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
// saveHostPortGroupID sets a special ID for a host virtual switch, composed of | ||
// the MOID for the concerned HostSystem and the port group's key. | ||
func saveHostPortGroupID(d *schema.ResourceData, hsID, name string) { | ||
d.SetId(fmt.Sprintf("%s:%s:%s", hostPortGroupIDPrefix, hsID, name)) | ||
} | ||
|
||
// splitHostPortGroupID splits a vsphere_host_port_group resource ID into its | ||
// counterparts: the prefix, the HostSystem ID, and the port group name. | ||
func splitHostPortGroupID(raw string) (string, string, error) { | ||
s := strings.SplitN(raw, ":", 3) | ||
if len(s) != 3 || s[0] != hostPortGroupIDPrefix || s[1] == "" || s[2] == "" { | ||
return "", "", fmt.Errorf("corrupt ID: %s", raw) | ||
} | ||
return s[1], s[2], nil | ||
} | ||
|
||
// portGroupIDsFromResourceID passes a resource's ID through | ||
// splitHostPortGroupID. | ||
func portGroupIDsFromResourceID(d *schema.ResourceData) (string, string, error) { | ||
return splitHostPortGroupID(d.Id()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
package vsphere | ||
|
||
import ( | ||
"fmt" | ||
|
||
"context" | ||
|
||
"github.com/hashicorp/terraform/helper/schema" | ||
"github.com/vmware/govmomi" | ||
) | ||
|
||
func resourceVSphereHostPortGroup() *schema.Resource { | ||
s := map[string]*schema.Schema{ | ||
"host_system_id": &schema.Schema{ | ||
Type: schema.TypeString, | ||
Description: "The managed object ID of the host to set the virtual switch up on.", | ||
Required: true, | ||
ForceNew: true, | ||
}, | ||
"computed_policy": &schema.Schema{ | ||
Type: schema.TypeMap, | ||
Description: "The effective network policy after inheritance. Note that this will look similar to, but is not the same, as the policy attributes defined in this resource.", | ||
Computed: true, | ||
}, | ||
"key": &schema.Schema{ | ||
Type: schema.TypeString, | ||
Description: "The linkable identifier for this port group.", | ||
Computed: true, | ||
}, | ||
"ports": &schema.Schema{ | ||
Type: schema.TypeSet, | ||
Description: "The ports that currently exist and are used on this port group.", | ||
Computed: true, | ||
MaxItems: 1, | ||
Elem: portGroupPortSchema(), | ||
}, | ||
} | ||
mergeSchema(s, schemaHostPortGroupSpec()) | ||
|
||
// Transform any necessary fields in the schema that need to be updated | ||
// specifically for this resource. | ||
s["active_nics"].Optional = true | ||
s["standby_nics"].Optional = true | ||
|
||
return &schema.Resource{ | ||
Create: resourceVSphereHostPortGroupCreate, | ||
Read: resourceVSphereHostPortGroupRead, | ||
Update: resourceVSphereHostPortGroupUpdate, | ||
Delete: resourceVSphereHostPortGroupDelete, | ||
Schema: s, | ||
} | ||
} | ||
|
||
func resourceVSphereHostPortGroupCreate(d *schema.ResourceData, meta interface{}) error { | ||
client := meta.(*govmomi.Client) | ||
name := d.Get("name").(string) | ||
hsID := d.Get("host_system_id").(string) | ||
ns, err := hostNetworkSystemFromHostSystemID(client, hsID) | ||
if err != nil { | ||
return fmt.Errorf("error loading network system: %s", err) | ||
} | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), defaultAPITimeout) | ||
defer cancel() | ||
spec := expandHostPortGroupSpec(d) | ||
if err := ns.AddPortGroup(ctx, *spec); err != nil { | ||
return fmt.Errorf("error adding port group: %s", err) | ||
} | ||
|
||
saveHostPortGroupID(d, hsID, name) | ||
return resourceVSphereHostPortGroupRead(d, meta) | ||
} | ||
|
||
func resourceVSphereHostPortGroupRead(d *schema.ResourceData, meta interface{}) error { | ||
client := meta.(*govmomi.Client) | ||
hsID, name, err := portGroupIDsFromResourceID(d) | ||
if err != nil { | ||
return err | ||
} | ||
ns, err := hostNetworkSystemFromHostSystemID(client, hsID) | ||
if err != nil { | ||
return fmt.Errorf("error loading host network system: %s", err) | ||
} | ||
|
||
pg, err := hostPortGroupFromName(meta.(*govmomi.Client), ns, name) | ||
if err != nil { | ||
return fmt.Errorf("error fetching port group data: %s", err) | ||
} | ||
|
||
if err := flattenHostPortGroupSpec(d, &pg.Spec); err != nil { | ||
return fmt.Errorf("error setting resource data: %s", err) | ||
} | ||
|
||
d.Set("key", pg.Key) | ||
cpm, err := calculateComputedPolicy(pg.ComputedPolicy) | ||
if err != nil { | ||
return err | ||
} | ||
if err := d.Set("computed_policy", cpm); err != nil { | ||
return fmt.Errorf("error saving effective policy to state: %s", err) | ||
} | ||
if err := d.Set("ports", calculatePorts(pg.Port)); err != nil { | ||
return fmt.Errorf("error setting port list: %s", err) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func resourceVSphereHostPortGroupUpdate(d *schema.ResourceData, meta interface{}) error { | ||
client := meta.(*govmomi.Client) | ||
hsID, name, err := portGroupIDsFromResourceID(d) | ||
if err != nil { | ||
return err | ||
} | ||
ns, err := hostNetworkSystemFromHostSystemID(client, hsID) | ||
if err != nil { | ||
return fmt.Errorf("error loading host network system: %s", err) | ||
} | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), defaultAPITimeout) | ||
defer cancel() | ||
spec := expandHostPortGroupSpec(d) | ||
if err := ns.UpdatePortGroup(ctx, name, *spec); err != nil { | ||
return fmt.Errorf("error updating port group: %s", err) | ||
} | ||
|
||
return resourceVSphereHostPortGroupRead(d, meta) | ||
} | ||
|
||
func resourceVSphereHostPortGroupDelete(d *schema.ResourceData, meta interface{}) error { | ||
client := meta.(*govmomi.Client) | ||
hsID, name, err := portGroupIDsFromResourceID(d) | ||
if err != nil { | ||
return err | ||
} | ||
ns, err := hostNetworkSystemFromHostSystemID(client, hsID) | ||
if err != nil { | ||
return fmt.Errorf("error loading host network system: %s", err) | ||
} | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), defaultAPITimeout) | ||
defer cancel() | ||
if err := ns.RemovePortGroup(ctx, name); err != nil { | ||
return fmt.Errorf("error deleting port group: %s", err) | ||
} | ||
|
||
return nil | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thoughts on adding
ValidateFunc: validation.IntBetween(0, 4095),
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will add it!