1
0
mirror of https://github.com/vmware/vsphere-automation-sdk-python.git synced 2024-11-22 01:39:58 -05:00

Remove tabulate from the dependency list

Signed-off-by: het <het@vmware.com>
This commit is contained in:
het 2018-11-22 15:51:21 +08:00
parent a6ebd9bc1b
commit 18b2ed120a
15 changed files with 494 additions and 526 deletions

View File

@ -1,7 +1,6 @@
pyVmomi >= 6.7 pyVmomi >= 6.7
suds ; python_version < '3' suds ; python_version < '3'
suds-jurko ; python_version >= '3.0' suds-jurko ; python_version >= '3.0'
tabulate
vapi-client-bindings == 1.5.0 vapi-client-bindings == 1.5.0
vmc-client-bindings vmc-client-bindings
vapi-vmc-client vapi-vmc-client

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,7 +14,6 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
from time import sleep from time import sleep
from tabulate import tabulate
from com.vmware.vmc.model_client import Task from com.vmware.vmc.model_client import Task
@ -44,8 +43,8 @@ def wait_for_task(task_client, org_id, task_id, interval_sec=60):
print('\nTask {} cancelled'.format(task_id)) print('\nTask {} cancelled'.format(task_id))
return False return False
else: else:
print("Estimated time remaining: {} minutes". print("Estimated time remaining: {} minutes".format(
format(task.estimated_remaining_minutes)) task.estimated_remaining_minutes))
sleep(interval_sec) sleep(interval_sec)
@ -56,9 +55,7 @@ def list_all_tasks(task_client, org_id):
:param org_id: organization id :param org_id: organization id
""" """
tasks = task_client.list(org_id) tasks = task_client.list(org_id)
headers = ['ID', 'Status', 'Progress', 'Started', 'User']
table = []
for task in tasks: for task in tasks:
table.append([task.id, task.status, task.progress_percent, print('ID: {}, Status: {}, Progress: {}, Started: {}, User: {}'.format(
task.start_time, task.user_name]) task.id, task.status, task.progress_percent, task.start_time,
print(tabulate(table, headers)) task.user_name))

View File

@ -16,8 +16,8 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
import argparse import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate from com.vmware.vmc.model_client import DnsForwarders
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
@ -162,9 +162,7 @@ class DNSCrud(object):
def print_output(self, dns): def print_output(self, dns):
# DNS IP address might be empty # DNS IP address might be empty
ips = getattr(dns.forwarders, 'ip_address', []) ips = getattr(dns.forwarders, 'ip_address', [])
print('Name: {}, IP Addresses: {}'.format(dns.name, ips))
result = [[dns.name, ips]]
print(tabulate(result, ['Name', 'IP Addresses']))
def main(): def main():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved. * Copyright (c) VMware, Inc. 2018. All Rights Reserved.
@ -16,8 +15,10 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
import argparse import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate from com.vmware.vmc.model_client import (AddressFWSourceDestination,
Application, FirewallRules,
Nsxfirewallrule, Nsxfirewallservice)
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
@ -33,29 +34,33 @@ class FirewallRulesCrud(object):
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id', parser.add_argument(
required=True, '-o', '--org-id', required=True, help='Organization identifier.')
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id', parser.add_argument(
required=True, '-s', '--sddc-id', required=True, help='Sddc Identifier.')
help='Sddc Identifier.')
parser.add_argument('--rule-name', parser.add_argument(
'--rule-name',
default='Sample Firewall Rule', default='Sample Firewall Rule',
help='Name of the new firewall rule') help='Name of the new firewall rule')
parser.add_argument('--use-compute-gateway', parser.add_argument(
'--use-compute-gateway',
action='store_true', action='store_true',
default=False, default=False,
help='Use compute gateway. Default is using ' help='Use compute gateway. Default is using '
'management gateway') 'management gateway')
parser.add_argument('-c', '--cleardata', parser.add_argument(
'-c',
'--cleardata',
action='store_true', action='store_true',
help='Clean up after sample run') help='Clean up after sample run')
args = parser.parse_args() args = parser.parse_args()
@ -74,13 +79,14 @@ class FirewallRulesCrud(object):
# Check if the organization exists # Check if the organization exists
orgs = self.vmc_client.Orgs.list() orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]: if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id)) raise ValueError("Org with ID {} doesn't exist".format(
self.org_id))
# Check if the SDDC exists # Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id) sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]: if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}". raise ValueError("SDDC with ID {} doesn't exist in org {}".format(
format(self.sddc_id, self.org_id)) self.sddc_id, self.org_id))
def create_firewall_rule(self): def create_firewall_rule(self):
@ -91,8 +97,7 @@ class FirewallRulesCrud(object):
print('# List network gateway edges:') print('# List network gateway edges:')
edges = self.vmc_client.orgs.sddcs.networks.Edges.get( edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data edge_type='gatewayServices').edge_page.data
print(' Management Gateway ID: {}'.format(edges[0].id)) print(' Management Gateway ID: {}'.format(edges[0].id))
@ -104,8 +109,10 @@ class FirewallRulesCrud(object):
# Construct an destination object for the new firewall rule # Construct an destination object for the new firewall rule
# You can use one of following destination IP addresses # You can use one of following destination IP addresses
# IPs for vCenter # IPs for vCenter
ip_address = [sddc.resource_config.vc_public_ip, ip_address = [
sddc.resource_config.vc_management_ip] sddc.resource_config.vc_public_ip,
sddc.resource_config.vc_management_ip
]
# TODO: IPs for ESXi # TODO: IPs for ESXi
# TODO: IPs for Site Recovery Manager # TODO: IPs for Site Recovery Manager
@ -121,7 +128,8 @@ class FirewallRulesCrud(object):
vnic_group_id=[]) vnic_group_id=[])
# Construct a new NSX firewall rule object # Construct a new NSX firewall rule object
self.nfwr = Nsxfirewallrule(rule_type='user', self.nfwr = Nsxfirewallrule(
rule_type='user',
name=self.rule_name, name=self.rule_name,
enabled=True, enabled=True,
action='accept', action='accept',
@ -134,11 +142,13 @@ class FirewallRulesCrud(object):
logging_enabled=False, logging_enabled=False,
application=Application( application=Application(
application_id=[], application_id=[],
service=[Nsxfirewallservice( service=[
Nsxfirewallservice(
source_port=['any'], source_port=['any'],
protocol='TCP', protocol='TCP',
port=['443'], port=['443'],
icmp_type=None)])) icmp_type=None)
]))
self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.add( self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.add(
org=self.org_id, org=self.org_id,
@ -152,9 +162,7 @@ class FirewallRulesCrud(object):
print('\n# Example: List basic firewall rule specs') print('\n# Example: List basic firewall rule specs')
fw_config = self.vmc_client.orgs.sddcs.networks.edges.firewall.Config.get( fw_config = self.vmc_client.orgs.sddcs.networks.edges.firewall.Config.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, edge_id=self.edge_id)
sddc=self.sddc_id,
edge_id=self.edge_id)
fw_rules = fw_config.firewall_rules.firewall_rules fw_rules = fw_config.firewall_rules.firewall_rules
@ -163,8 +171,8 @@ class FirewallRulesCrud(object):
self.rule_id = r.rule_id self.rule_id = r.rule_id
break break
else: else:
raise Exception("Can't find firewall rule with name {}". raise Exception("Can't find firewall rule with name {}".format(
format(self.rule_name)) self.rule_name))
rule = self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.get( rule = self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.get(
org=self.org_id, org=self.org_id,
@ -205,18 +213,16 @@ class FirewallRulesCrud(object):
sddc=self.sddc_id, sddc=self.sddc_id,
edge_id=self.edge_id, edge_id=self.edge_id,
rule_id=self.rule_id) rule_id=self.rule_id)
print('\n# Example: Firewall rule {} is deleted'. print('\n# Example: Firewall rule {} is deleted'.format(
format(self.rule_name)) self.rule_name))
def print_output(self, rule): def print_output(self, rule):
result = [[rule.name, rule.action, rule.source.ip_address, print(
'Name: {}, Action: {}, Source IPs: {}, Destination IPs: {},Service Protocol: {}, Service Port: {}'
.format(rule.name, rule.action, rule.source.ip_address,
rule.destination.ip_address, rule.destination.ip_address,
rule.application.service[0].protocol, rule.application.service[0].protocol,
rule.application.service[0].port]] rule.application.service[0].port))
print(tabulate(result, ['Name', 'Action', 'Source IPs',
'Destination IPs', 'Service Protocol',
'Service Port']))
def main(): def main():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved. * Copyright (c) VMware, Inc. 2018. All Rights Reserved.
@ -16,8 +15,8 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
import argparse import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate from com.vmware.vmc.model_client import Ipsec, IpsecSite, IpsecSites, Subnets
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
@ -33,49 +32,58 @@ class IpsecVPNsCrud(object):
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id', parser.add_argument(
required=True, '-o', '--org-id', required=True, help='Organization identifier.')
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id', parser.add_argument(
required=True, '-s', '--sddc-id', required=True, help='Sddc Identifier.')
help='Sddc Identifier.')
parser.add_argument('--use-compute-gateway', parser.add_argument(
'--use-compute-gateway',
action='store_true', action='store_true',
default=False, default=False,
help='Use compute gateway. Default is using ' help='Use compute gateway. Default is using '
'management gateway') 'management gateway')
parser.add_argument('--vpn-name', parser.add_argument(
'--vpn-name',
default='Sample IPsec VPN', default='Sample IPsec VPN',
help='Name of the new VPN') help='Name of the new VPN')
parser.add_argument('--public-ip', parser.add_argument(
'--public-ip',
default='10.10.10.10', default='10.10.10.10',
help='IP (IPv4) address or FQDN of the Peer') help='IP (IPv4) address or FQDN of the Peer')
parser.add_argument('--private-ip', parser.add_argument(
'--private-ip',
default='192.168.10.10', default='192.168.10.10',
help='Local IP of the IPsec Site') help='Local IP of the IPsec Site')
parser.add_argument('--remote-networks', parser.add_argument(
'--remote-networks',
default='192.168.20.10/24', default='192.168.20.10/24',
help='Peer subnets for which VPN is configured') help='Peer subnets for which VPN is configured')
parser.add_argument('--local-networks', parser.add_argument(
'--local-networks',
default='192.168.30.10/24', default='192.168.30.10/24',
help='Local subnets for which VPN is configured') help='Local subnets for which VPN is configured')
parser.add_argument('--key', parser.add_argument(
'--key',
default='00000000', default='00000000',
help='Pre Shared Key for the IPsec Site') help='Pre Shared Key for the IPsec Site')
parser.add_argument('-c', '--cleardata', parser.add_argument(
'-c',
'--cleardata',
action='store_true', action='store_true',
help='Clean up after sample run') help='Clean up after sample run')
args = parser.parse_args() args = parser.parse_args()
@ -98,18 +106,18 @@ class IpsecVPNsCrud(object):
# Check if the organization exists # Check if the organization exists
orgs = self.vmc_client.Orgs.list() orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]: if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id)) raise ValueError("Org with ID {} doesn't exist".format(
self.org_id))
# Check if the SDDC exists # Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id) sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]: if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}". raise ValueError("SDDC with ID {} doesn't exist in org {}".format(
format(self.sddc_id, self.org_id)) self.sddc_id, self.org_id))
print('\n# Setup: List network gateway edges:') print('\n# Setup: List network gateway edges:')
edges = self.vmc_client.orgs.sddcs.networks.Edges.get( edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data edge_type='gatewayServices').edge_page.data
print(' Management Gateway ID: {}'.format(edges[0].id)) print(' Management Gateway ID: {}'.format(edges[0].id))
@ -134,8 +142,7 @@ class IpsecVPNsCrud(object):
enabled=True, enabled=True,
local_subnets=Subnets(subnets=[self.local_networks])) local_subnets=Subnets(subnets=[self.local_networks]))
ipsec = Ipsec(enabled=True, ipsec = Ipsec(enabled=True, sites=IpsecSites(sites=[ipsec_site]))
sites=IpsecSites(sites=[ipsec_site]))
# TODO: Find out how to add ipsec networks. # TODO: Find out how to add ipsec networks.
self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.update( self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.update(
@ -157,9 +164,7 @@ class IpsecVPNsCrud(object):
updated_name = 'Updated ' + self.vpn_name updated_name = 'Updated ' + self.vpn_name
ipsec = self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.get( ipsec = self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, edge_id=self.edge_id)
sddc=self.sddc_id,
edge_id=self.edge_id)
for site in ipsec.sites.sites: for site in ipsec.sites.sites:
if site.name == self.vpn_name: if site.name == self.vpn_name:
@ -178,32 +183,26 @@ class IpsecVPNsCrud(object):
def delete_vpn(self): def delete_vpn(self):
if self.cleanup: if self.cleanup:
self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.delete( self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.delete(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, edge_id=self.edge_id)
sddc=self.sddc_id, print('\n# Example: IPsec VPN {} is deleted'.format(self.vpn_name))
edge_id=self.edge_id)
print('\n# Example: IPsec VPN {} is deleted'.
format(self.vpn_name))
def get_vpn_by_name(self, name): def get_vpn_by_name(self, name):
sites = self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.get( sites = self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id,
sddc=self.sddc_id,
edge_id=self.edge_id).sites.sites edge_id=self.edge_id).sites.sites
for site in sites: for site in sites:
if site.name == name: if site.name == name:
return site return site
else: else:
raise Exception("Can't find IPsec VPN with name {}". raise Exception("Can't find IPsec VPN with name {}".format(
format(self.vpn_name)) self.vpn_name))
def print_output(self, site): def print_output(self, site):
result = [[site.name, site.site_id, site.peer_ip, site.peer_id, print(
site.peer_subnets, site.local_ip, site.local_subnets]] 'Name: {}, ID: {}, Public IPs: {}, Private IP: {}, Remote Networks: {}, Local Gateway IP: {}, Local Network {}'
.format(site.name, site.site_id, site.peer_ip, site.peer_id,
print(tabulate(result, ['Name', 'ID', 'Public IPs', 'Private IP', site.peer_subnets, site.local_ip, site.local_subnets))
'Remote Networks', 'Local Gateway IP',
'Local Network']))
def main(): def main():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved. * Copyright (c) VMware, Inc. 2018. All Rights Reserved.
@ -16,8 +15,12 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
import argparse import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate from com.vmware.vmc.model_client import (L2Extension, SddcNetwork,
SddcNetworkAddressGroups,
SddcNetworkAddressGroup,
SddcNetworkDhcpConfig,
SddcNetworkDhcpIpPool)
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
@ -33,31 +36,36 @@ class LogicalNetworkCrud(object):
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id', parser.add_argument(
required=True, '-o', '--org-id', required=True, help='Organization identifier.')
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id', parser.add_argument(
required=True, '-s', '--sddc-id', required=True, help='Sddc Identifier.')
help='Sddc Identifier.')
parser.add_argument('--network-name', parser.add_argument(
'--network-name',
default='Sample Logical Network', default='Sample Logical Network',
help='Name of the new logical network') help='Name of the new logical network')
parser.add_argument('--subnet', parser.add_argument(
'--subnet',
default='192.168.100.1/24', default='192.168.100.1/24',
help='Logical network subnet') help='Logical network subnet')
parser.add_argument('--dhcp-range', parser.add_argument(
'--dhcp-range',
default='192.168.100.2-192.168.100.254', default='192.168.100.2-192.168.100.254',
help='DHCP IP range for the logical network') help='DHCP IP range for the logical network')
parser.add_argument('-c', '--cleardata', parser.add_argument(
'-c',
'--cleardata',
action='store_true', action='store_true',
help='Clean up after sample run') help='Clean up after sample run')
args = parser.parse_args() args = parser.parse_args()
@ -75,61 +83,57 @@ class LogicalNetworkCrud(object):
# Check if the organization exists # Check if the organization exists
orgs = self.vmc_client.Orgs.list() orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]: if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id)) raise ValueError("Org with ID {} doesn't exist".format(
self.org_id))
# Check if the SDDC exists # Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id) sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]: if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}". raise ValueError("SDDC with ID {} doesn't exist in org {}".format(
format(self.sddc_id, self.org_id)) self.sddc_id, self.org_id))
# Delete logical networks with same name # Delete logical networks with same name
networks = self.vmc_client.orgs.sddcs.networks.Logical.get_0( networks = self.vmc_client.orgs.sddcs.networks.Logical.get_0(
org=self.org_id, org=self.org_id, sddc=self.sddc_id).data
sddc=self.sddc_id).data
for network in networks: for network in networks:
if network.name == self.network_name: if network.name == self.network_name:
self.vmc_client.orgs.sddcs.networks.Logical.delete( self.vmc_client.orgs.sddcs.networks.Logical.delete(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, network_id=network.id)
sddc=self.sddc_id,
network_id=network.id)
print('\n# Setup: Logical network "{}" ' print('\n# Setup: Logical network "{}" '
'with the same name is deleted'.format(network.id)) 'with the same name is deleted'.format(network.id))
def create_logical_network(self): def create_logical_network(self):
print('\n# Example: Add a logical network to the compute gateway') print('\n# Example: Add a logical network to the compute gateway')
edges = self.vmc_client.orgs.sddcs.networks.Edges.get( edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data edge_type='gatewayServices').edge_page.data
print(' Compute Gateway ID: {}'.format(edges[1].id)) print(' Compute Gateway ID: {}'.format(edges[1].id))
edge_id = edges[1].id edge_id = edges[1].id
# Construct a new NSX logical network spec # Construct a new NSX logical network spec
network = SddcNetwork( network = SddcNetwork(
subnets=SddcNetworkAddressGroups( subnets=SddcNetworkAddressGroups(address_groups=[
address_groups=[SddcNetworkAddressGroup( SddcNetworkAddressGroup(
prefix_length=self.prefix_length, prefix_length=self.prefix_length,
primary_address=self.primary_address)]), primary_address=self.primary_address)
]),
name=self.network_name, name=self.network_name,
cgw_id=edge_id, cgw_id=edge_id,
dhcp_configs=SddcNetworkDhcpConfig( dhcp_configs=SddcNetworkDhcpConfig(ip_pools=[
ip_pools=[SddcNetworkDhcpIpPool( SddcNetworkDhcpIpPool(
ip_range=self.dhcp_range, ip_range=self.dhcp_range, domain_name=None)
domain_name=None)])) ]))
self.vmc_client.orgs.sddcs.networks.Logical.create( self.vmc_client.orgs.sddcs.networks.Logical.create(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, sddc_network=network)
sddc=self.sddc_id,
sddc_network=network)
print('\n# New logical network "{}" is added'.format(self.network_name)) print('\n# New logical network "{}" is added'.format(
self.network_name))
def get_logical_network(self): def get_logical_network(self):
print('\n# Example: List all logical networks') print('\n# Example: List all logical networks')
networks = self.vmc_client.orgs.sddcs.networks.Logical.get_0( networks = self.vmc_client.orgs.sddcs.networks.Logical.get_0(
org=self.org_id, org=self.org_id, sddc=self.sddc_id).data
sddc=self.sddc_id).data
self.print_output(networks) self.print_output(networks)
@ -138,23 +142,19 @@ class LogicalNetworkCrud(object):
self.network_id = network.id self.network_id = network.id
break break
else: else:
raise Exception("Can't find logical network with name {}". raise Exception("Can't find logical network with name {}".format(
format(self.network_name)) self.network_name))
print('\n# Get the new logical network specs') print('\n# Get the new logical network specs')
network = self.vmc_client.orgs.sddcs.networks.Logical.get( network = self.vmc_client.orgs.sddcs.networks.Logical.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, network_id=self.network_id)
sddc=self.sddc_id,
network_id=self.network_id)
self.print_output([network]) self.print_output([network])
def update_logical_network(self): def update_logical_network(self):
print('\n# Example: Update the logical network') print('\n# Example: Update the logical network')
network = self.vmc_client.orgs.sddcs.networks.Logical.get( network = self.vmc_client.orgs.sddcs.networks.Logical.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, network_id=self.network_id)
sddc=self.sddc_id,
network_id=self.network_id)
network.l2_extension = L2Extension(123) network.l2_extension = L2Extension(123)
network.subnets = None network.subnets = None
network.dhcp_configs = None network.dhcp_configs = None
@ -166,9 +166,7 @@ class LogicalNetworkCrud(object):
sddc_network=network) sddc_network=network)
network = self.vmc_client.orgs.sddcs.networks.Logical.get( network = self.vmc_client.orgs.sddcs.networks.Logical.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, network_id=self.network_id)
sddc=self.sddc_id,
network_id=self.network_id)
print('# List the updated logical network specs') print('# List the updated logical network specs')
self.print_output([network]) self.print_output([network])
@ -176,21 +174,18 @@ class LogicalNetworkCrud(object):
def delete_logical_network(self): def delete_logical_network(self):
if self.cleanup: if self.cleanup:
self.vmc_client.orgs.sddcs.networks.Logical.delete( self.vmc_client.orgs.sddcs.networks.Logical.delete(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, network_id=self.network_id)
sddc=self.sddc_id, print('\n# Example: Logical network "{}" is deleted'.format(
network_id=self.network_id) self.network_name))
print('\n# Example: Logical network "{}" is deleted'.
format(self.network_name))
def print_output(self, networks): def print_output(self, networks):
table = []
for network in networks: for network in networks:
table.append([network.cgw_name, network.id, network.name, print('Gateway: {}, Network ID: {}, Network Name: {}, Subnets: {}'.
format(
network.cgw_name, network.id, network.name,
'{}/{}'.format( '{}/{}'.format(
network.subnets.address_groups[0].primary_address, network.subnets.address_groups[0].primary_address,
network.subnets.address_groups[0].prefix_length)]) network.subnets.address_groups[0].prefix_length)))
print(tabulate(table, ['Gateway', 'Network ID', 'Network Name',
'Subnets']))
def main(): def main():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved. * Copyright (c) VMware, Inc. 2018. All Rights Reserved.
@ -16,8 +15,7 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
import argparse import argparse
from com.vmware.vmc.model_client import * from com.vmware.vmc.model_client import Nsxnatrule, NatRules
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
@ -33,30 +31,34 @@ class NatRuleCrud(object):
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id', parser.add_argument(
required=True, '-o', '--org-id', required=True, help='Organization identifier.')
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id', parser.add_argument(
required=True, '-s', '--sddc-id', required=True, help='Sddc Identifier.')
help='Sddc Identifier.')
parser.add_argument('--public-ip', parser.add_argument(
help='Public IP range for the NAT rule') '--public-ip', help='Public IP range for the NAT rule')
parser.add_argument('--rule-description', parser.add_argument(
'--rule-description',
default='Sample NAT rule', default='Sample NAT rule',
help='Description for the rule') help='Description for the rule')
parser.add_argument('--internal-ip', parser.add_argument(
'--internal-ip',
default='192.168.200.1/24', default='192.168.200.1/24',
help='NAT rule subnet') help='NAT rule subnet')
parser.add_argument('-c', '--cleardata', parser.add_argument(
'-c',
'--cleardata',
action='store_true', action='store_true',
help='Clean up after sample run') help='Clean up after sample run')
args = parser.parse_args() args = parser.parse_args()
@ -77,17 +79,17 @@ class NatRuleCrud(object):
# Check if the organization exists # Check if the organization exists
orgs = self.vmc_client.Orgs.list() orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]: if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id)) raise ValueError("Org with ID {} doesn't exist".format(
self.org_id))
# Check if the SDDC exists # Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id) sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]: if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}". raise ValueError("SDDC with ID {} doesn't exist in org {}".format(
format(self.sddc_id, self.org_id)) self.sddc_id, self.org_id))
edges = self.vmc_client.orgs.sddcs.networks.Edges.get( edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data edge_type='gatewayServices').edge_page.data
print('\n# Setup: Compute Gateway ID: {}'.format(edges[1].id)) print('\n# Setup: Compute Gateway ID: {}'.format(edges[1].id))
self.edge_id = edges[1].id self.edge_id = edges[1].id
@ -107,7 +109,8 @@ class NatRuleCrud(object):
print('\n# Example: Add a NAT rule to the compute gateway') print('\n# Example: Add a NAT rule to the compute gateway')
# Construct a new NSX NAT rule spec # Construct a new NSX NAT rule spec
rule = Nsxnatrule(vnic='0', rule = Nsxnatrule(
vnic='0',
rule_type='user', rule_type='user',
action='dnat', # Supported types are DNAT|SNAT action='dnat', # Supported types are DNAT|SNAT
protocol='tcp', protocol='tcp',
@ -129,8 +132,7 @@ class NatRuleCrud(object):
def get_net_rule(self): def get_net_rule(self):
print('\n# Example: List all NAT rules') print('\n# Example: List all NAT rules')
rules = self.vmc_client.orgs.sddcs.networks.edges.nat.Config.get( rules = self.vmc_client.orgs.sddcs.networks.edges.nat.Config.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id,
sddc=self.sddc_id,
edge_id=self.edge_id).rules.nat_rules_dtos edge_id=self.edge_id).rules.nat_rules_dtos
self.print_output(rules) self.print_output(rules)
@ -161,13 +163,12 @@ class NatRuleCrud(object):
sddc=self.sddc_id, sddc=self.sddc_id,
edge_id=self.edge_id, edge_id=self.edge_id,
rule_id=self.rule_id) rule_id=self.rule_id)
print('\n# Example: NAT rule "{}" is deleted'. print('\n# Example: NAT rule "{}" is deleted'.format(
format(self.rule_description)) self.rule_description))
def get_nat_rules_by_description(self, description): def get_nat_rules_by_description(self, description):
rules = self.vmc_client.orgs.sddcs.networks.edges.nat.Config.get( rules = self.vmc_client.orgs.sddcs.networks.edges.nat.Config.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id,
sddc=self.sddc_id,
edge_id=self.edge_id).rules.nat_rules_dtos edge_id=self.edge_id).rules.nat_rules_dtos
result = [] result = []
for rule in rules: for rule in rules:
@ -176,14 +177,12 @@ class NatRuleCrud(object):
return result return result
def print_output(self, rules): def print_output(self, rules):
table = []
for rule in rules: for rule in rules:
table.append([rule.description, rule.rule_id, rule.action, print(
'Description: {}, Rule ID: {}, Action: {}, Public IP: {}, Public Ports: {}, Internal IP: {}, Internal Ports: {}'
.format(rule.description, rule.rule_id, rule.action,
rule.original_address, rule.original_port, rule.original_address, rule.original_port,
rule.translated_address, rule.translated_port]) rule.translated_address, rule.translated_port))
print(tabulate(table, ['Description', 'Rule ID', 'Action',
'Public IP', 'Public Ports',
'Internal IP', 'Internal Ports']))
def main(): def main():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved. * Copyright (c) VMware, Inc. 2018. All Rights Reserved.
@ -16,8 +15,7 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
import argparse import argparse
from com.vmware.vmc.model_client import * from com.vmware.vmc.model_client import SddcAllocatePublicIpSpec
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
from samples.vmc.helpers.vmc_task_helper import wait_for_task from samples.vmc.helpers.vmc_task_helper import wait_for_task
@ -35,23 +33,26 @@ class PublicIPsCrud(object):
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id', parser.add_argument(
required=True, '-o', '--org-id', required=True, help='Organization identifier.')
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id', parser.add_argument(
required=True, '-s', '--sddc-id', required=True, help='Sddc Identifier.')
help='Sddc Identifier.')
parser.add_argument('--notes', parser.add_argument(
'--notes',
default='Sample public IP', default='Sample public IP',
help='Notes of the new public IP') help='Notes of the new public IP')
parser.add_argument('-c', '--cleardata', parser.add_argument(
'-c',
'--cleardata',
action='store_true', action='store_true',
help='Clean up after sample run') help='Clean up after sample run')
args = parser.parse_args() args = parser.parse_args()
@ -67,64 +68,58 @@ class PublicIPsCrud(object):
# Check if the organization exists # Check if the organization exists
orgs = self.vmc_client.Orgs.list() orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]: if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id)) raise ValueError("Org with ID {} doesn't exist".format(
self.org_id))
# Check if the SDDC exists # Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id) sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]: if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}". raise ValueError("SDDC with ID {} doesn't exist in org {}".format(
format(self.sddc_id, self.org_id)) self.sddc_id, self.org_id))
def request_public_ip(self): def request_public_ip(self):
print('\n# Example: Request a new IP for SDDC') print('\n# Example: Request a new IP for SDDC')
ip_spec = SddcAllocatePublicIpSpec(names=[self.notes], count=1) ip_spec = SddcAllocatePublicIpSpec(names=[self.notes], count=1)
task = self.vmc_client.orgs.sddcs.Publicips.create( task = self.vmc_client.orgs.sddcs.Publicips.create(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, spec=ip_spec)
sddc=self.sddc_id,
spec=ip_spec)
wait_for_task(task_client=self.vmc_client.orgs.Tasks, wait_for_task(
task_client=self.vmc_client.orgs.Tasks,
org_id=self.org_id, org_id=self.org_id,
task_id=task.id, task_id=task.id,
interval_sec=2) interval_sec=2)
ips = self.vmc_client.orgs.sddcs.Publicips.list( ips = self.vmc_client.orgs.sddcs.Publicips.list(
org=self.org_id, org=self.org_id, sddc=self.sddc_id)
sddc=self.sddc_id)
for ip in ips: for ip in ips:
if ip.name == self.notes: if ip.name == self.notes:
self.ip_id = ip.allocation_id self.ip_id = ip.allocation_id
print('# Successfully requested public IP {}'. print('# Successfully requested public IP {}'.format(
format(ip.public_ip)) ip.public_ip))
break break
else: else:
raise Exception("Can't find public IP with notes {}". raise Exception("Can't find public IP with notes {}".format(
format(self.notes)) self.notes))
def get_public_ip(self): def get_public_ip(self):
print('\n# Example: List all public IPs for the SDDC') print('\n# Example: List all public IPs for the SDDC')
ips = self.vmc_client.orgs.sddcs.Publicips.list( ips = self.vmc_client.orgs.sddcs.Publicips.list(
org=self.org_id, org=self.org_id, sddc=self.sddc_id)
sddc=self.sddc_id)
self.print_output(ips) self.print_output(ips)
print('\n# Example: Get the specific IP with ID {}'.format(self.ip_id)) print('\n# Example: Get the specific IP with ID {}'.format(self.ip_id))
ip = self.vmc_client.orgs.sddcs.Publicips.get( ip = self.vmc_client.orgs.sddcs.Publicips.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, id=self.ip_id)
sddc=self.sddc_id,
id=self.ip_id)
self.print_output([ip]) self.print_output([ip])
def update_public_ip(self): def update_public_ip(self):
print('\n# Example: Update the public IP notes') print('\n# Example: Update the public IP notes')
ip = self.vmc_client.orgs.sddcs.Publicips.get( ip = self.vmc_client.orgs.sddcs.Publicips.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, id=self.ip_id)
sddc=self.sddc_id,
id=self.ip_id)
ip.name = 'Updated ' + ip.name ip.name = 'Updated ' + ip.name
self.vmc_client.orgs.sddcs.Publicips.update( self.vmc_client.orgs.sddcs.Publicips.update(
@ -135,9 +130,7 @@ class PublicIPsCrud(object):
sddc_public_ip_object=ip) sddc_public_ip_object=ip)
ip = self.vmc_client.orgs.sddcs.Publicips.get( ip = self.vmc_client.orgs.sddcs.Publicips.get(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, id=self.ip_id)
sddc=self.sddc_id,
id=self.ip_id)
print('# List the updated public IP') print('# List the updated public IP')
self.print_output([ip]) self.print_output([ip])
@ -145,17 +138,13 @@ class PublicIPsCrud(object):
def delete_public_ip(self): def delete_public_ip(self):
if self.cleanup: if self.cleanup:
self.vmc_client.orgs.sddcs.Publicips.delete( self.vmc_client.orgs.sddcs.Publicips.delete(
org=self.org_id, org=self.org_id, sddc=self.sddc_id, id=self.ip_id)
sddc=self.sddc_id, print('\n# Example: Public IP "{}" is deleted'.format(self.notes))
id=self.ip_id)
print('\n# Example: Public IP "{}" is deleted'.
format(self.notes))
def print_output(self, ips): def print_output(self, ips):
result = []
for ip in ips: for ip in ips:
result.append([ip.public_ip, ip.allocation_id, ip.name]) print('Public IP: {}, ID: {}, Notes: {}'.format(
print(tabulate(result, ['Public IP', 'ID', 'Notes'])) ip.public_ip, ip.allocation_id, ip.name))
def main(): def main():

View File

@ -1,8 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -18,7 +17,6 @@ __author__ = 'VMware, Inc.'
import requests import requests
import argparse import argparse
import atexit import atexit
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
@ -41,7 +39,9 @@ class OperationsOnOrganizations(object):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
@ -59,25 +59,21 @@ class OperationsOnOrganizations(object):
raise ValueError('The sample requires at least one org associated' raise ValueError('The sample requires at least one org associated'
'with the calling user') 'with the calling user')
print("\n# Example: List organizations") print("\n# Example: List organizations")
table = []
for org in orgs: for org in orgs:
table.append([org.id, org.display_name]) print('ID: {}, Display Name: {}'.format(org.id, org.display_name))
print(tabulate(table, ['ID', 'Display Name']))
self.org = orgs[0] self.org = orgs[0]
def get_org_detail(self): def get_org_detail(self):
org = self.org org = self.org
print('\n# Example: List details of the first organization {}:'. print('\n# Example: List details of the first organization {}:'.format(
format(org.id)) org.id))
headers = ['ID', 'Display Name', 'Name', 'Created', 'Updated', print(
'Project State', 'SLA'] 'ID: {}, Display Name: {}, Name: {}, Created: {}, Updated: {}, Project State: {}'
data = [org.id, org.display_name, org.name, .format(org.id, org.display_name, org.name,
org.created.strftime('%m/%d/%Y'), org.created.strftime('%m/%d/%Y'),
org.updated.strftime('%m/%d/%Y'), org.updated.strftime('%m/%d/%Y'), org.project_state))
org.project_state, org.sla]
print(tabulate([data], headers))
def main(): def main():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved. * Copyright (c) VMware, Inc. 2018. All Rights Reserved.
@ -21,7 +20,6 @@ import argparse
from com.vmware.vapi.std.errors_client import NotFound from com.vmware.vapi.std.errors_client import NotFound
from com.vmware.vmc.model_client import ErrorResponse from com.vmware.vmc.model_client import ErrorResponse
from six.moves.urllib import parse from six.moves.urllib import parse
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
from vmware.vapi.vsphere.client import create_vsphere_client from vmware.vapi.vsphere.client import create_vsphere_client
@ -38,17 +36,17 @@ class ConnectTovSphereWithDefaultCredentials(object):
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id', parser.add_argument(
required=True, '-o', '--org-id', required=True, help='Organization identifier.')
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id', parser.add_argument(
required=True, '-s', '--sddc-id', required=True, help='Sddc Identifier.')
help='Sddc Identifier.')
args = parser.parse_args() args = parser.parse_args()
self.refresh_token = args.refresh_token self.refresh_token = args.refresh_token
@ -59,12 +57,14 @@ class ConnectTovSphereWithDefaultCredentials(object):
# Connect to VMware Cloud on AWS # Connect to VMware Cloud on AWS
vmc_client = create_vmc_client(self.refresh_token) vmc_client = create_vmc_client(self.refresh_token)
print('\n# Example: Successfully login to VMware Cloud on AWS instance') print(
'\n# Example: Successfully login to VMware Cloud on AWS instance')
# Check if the organization exists # Check if the organization exists
orgs = vmc_client.Orgs.list() orgs = vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]: if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id)) raise ValueError("Org with ID {} doesn't exist".format(
self.org_id))
# Check if the SDDC exists # Check if the SDDC exists
try: try:
@ -78,18 +78,20 @@ class ConnectTovSphereWithDefaultCredentials(object):
# Connect to vSphere client using the initial cloud admin credentials. # Connect to vSphere client using the initial cloud admin credentials.
# Please use the new credentials to login after you reset the default one. # Please use the new credentials to login after you reset the default one.
vsphere_client = create_vsphere_client(server, vsphere_client = create_vsphere_client(
server,
username=sddc.resource_config.cloud_username, username=sddc.resource_config.cloud_username,
password=sddc.resource_config.cloud_password) password=sddc.resource_config.cloud_password)
print("\n# Example: Successfully connect to vCenter at '{}'".format(server)) print("\n# Example: Successfully connect to vCenter at '{}'".format(
server))
# List VMs in the vSphere instance # List VMs in the vSphere instance
vms = vsphere_client.vcenter.VM.list() vms = vsphere_client.vcenter.VM.list()
table = []
for vm_summary in vms:
table.append([vm_summary.vm, vm_summary.name])
print('\n# Example: List VMs in the vSphere') print('\n# Example: List VMs in the vSphere')
print(tabulate(table, ['VM ID', 'VM Name'])) for vm_summary in vms:
print('VM ID: {}, VM Name: {}'.format(vm_summary.vm,
vm_summary.name))
def main(): def main():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017. All Rights Reserved.
@ -21,7 +20,6 @@ from random import randrange
from com.vmware.vapi.std.errors_client import InvalidRequest from com.vmware.vapi.std.errors_client import InvalidRequest
from com.vmware.vmc.model_client import AwsSddcConfig, ErrorResponse, AccountLinkSddcConfig, SddcConfig from com.vmware.vmc.model_client import AwsSddcConfig, ErrorResponse, AccountLinkSddcConfig, SddcConfig
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client from vmware.vapi.vmc.client import create_vmc_client
from samples.vmc.helpers.vmc_task_helper import wait_for_task from samples.vmc.helpers.vmc_task_helper import wait_for_task
@ -38,39 +36,50 @@ class CreateDeleteSDDC(object):
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('-r', '--refresh-token', parser.add_argument(
'-r',
'--refresh-token',
required=True, required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id', parser.add_argument(
required=True, '-o', '--org-id', required=True, help='Organization identifier.')
help='Organization identifier.')
parser.add_argument('-sn', '--sddc-name', parser.add_argument(
'-sn',
'--sddc-name',
help="Name of the SDDC to be created. " help="Name of the SDDC to be created. "
"Default is 'Sample SDDC xx'") "Default is 'Sample SDDC xx'")
parser.add_argument('--region', parser.add_argument('--region', default='US_WEST_2', help='AWS Region')
default='us-west-2',
help='AWS Region')
parser.add_argument('-i', '--interval-sec', parser.add_argument(
'-i',
'--interval-sec',
default=60, default=60,
help='Task pulling interval in sec') help='Task pulling interval in sec')
parser.add_argument('-ls', '--listsddc', parser.add_argument(
'-ls',
'--listsddc',
action='store_true', action='store_true',
help='List SDDCs in the specified Org') help='List SDDCs in the specified Org')
parser.add_argument('-cs', '--createsddc', parser.add_argument(
'-cs',
'--createsddc',
action='store_true', action='store_true',
help='Create an SDDC in the specified Org') help='Create an SDDC in the specified Org')
parser.add_argument('-ds', '--deletesddc', parser.add_argument(
'-ds',
'--deletesddc',
action='store_true', action='store_true',
help='Deletes the SDDC in the specified Org ') help='Deletes the SDDC in the specified Org ')
parser.add_argument('-c', '--cleardata', parser.add_argument(
'-c',
'--cleardata',
action='store_true', action='store_true',
help='Clean up after sample run') help='Clean up after sample run')
@ -84,7 +93,8 @@ class CreateDeleteSDDC(object):
self.deletesddc = args.deletesddc self.deletesddc = args.deletesddc
self.cleanup = args.cleardata self.cleanup = args.cleardata
self.sddc_id = None self.sddc_id = None
self.sddc_name = args.sddc_name or 'Sample SDDC {}'.format(randrange(100)) self.sddc_name = args.sddc_name or 'Sample SDDC {}'.format(
randrange(100))
self.interval_sec = int(args.interval_sec) self.interval_sec = int(args.interval_sec)
# Login to VMware Cloud on AWS # Login to VMware Cloud on AWS
@ -95,42 +105,46 @@ class CreateDeleteSDDC(object):
# Check if the organization exists # Check if the organization exists
orgs = self.vmc_client.Orgs.list() orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]: if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id)) raise ValueError("Org with ID {} doesn't exist".format(
self.org_id))
def create_sddc(self): def create_sddc(self):
print('\n# Example: Create a SDDC ({}) in org {}:'. print('\n# Example: Create a SDDC ({}) in org {}:'.format(
format(self.sddc_name, self.org_id)) self.sddc_name, self.org_id))
account_id = self.vmc_client.orgs.account_link.ConnectedAccounts.get( account_id = self.vmc_client.orgs.account_link.ConnectedAccounts.get(
self.org_id)[0].id self.org_id)[0].id
vpc_map = self.vmc_client.orgs.account_link.CompatibleSubnets.get( vpc_map = self.vmc_client.orgs.account_link.CompatibleSubnets.get(
org=self.org_id, org=self.org_id, linked_account_id=account_id).vpc_map
linked_account_id=account_id).vpc_map
customer_subnet_id = self.get_subnet_id(vpc_map) customer_subnet_id = self.get_subnet_id(vpc_map)
if not customer_subnet_id: if not customer_subnet_id:
raise ValueError('No available subnet for region {}'.format(self.region)) raise ValueError('No available subnet for region {}'.format(
self.region))
sddc_config = AwsSddcConfig( sddc_config = AwsSddcConfig(
region=self.region, region=self.region,
name=self.sddc_name, name=self.sddc_name,
account_link_sddc_config=[AccountLinkSddcConfig( account_link_sddc_config=[
AccountLinkSddcConfig(
customer_subnet_ids=[customer_subnet_id], customer_subnet_ids=[customer_subnet_id],
connected_account_id=account_id)], connected_account_id=account_id)
],
provider=os.environ.get('VMC_PROVIDER', SddcConfig.PROVIDER_AWS), provider=os.environ.get('VMC_PROVIDER', SddcConfig.PROVIDER_AWS),
num_hosts=1, num_hosts=1,
deployment_type=SddcConfig.DEPLOYMENT_TYPE_SINGLEAZ) deployment_type=SddcConfig.DEPLOYMENT_TYPE_SINGLEAZ)
try: try:
task = self.vmc_client.orgs.Sddcs.create(org=self.org_id, task = self.vmc_client.orgs.Sddcs.create(
sddc_config=sddc_config) org=self.org_id, sddc_config=sddc_config)
except InvalidRequest as e: except InvalidRequest as e:
# Convert InvalidRequest to ErrorResponse to get error message # Convert InvalidRequest to ErrorResponse to get error message
error_response = e.data.convert_to(ErrorResponse) error_response = e.data.convert_to(ErrorResponse)
raise Exception(error_response.error_messages) raise Exception(error_response.error_messages)
wait_for_task(task_client=self.vmc_client.orgs.Tasks, wait_for_task(
task_client=self.vmc_client.orgs.Tasks,
org_id=self.org_id, org_id=self.org_id,
task_id=task.id, task_id=task.id,
interval_sec=self.interval_sec) interval_sec=self.interval_sec)
@ -141,23 +155,24 @@ class CreateDeleteSDDC(object):
self.print_output([sddc]) self.print_output([sddc])
def delete_sddc(self): def delete_sddc(self):
print('\n# Example: Delete SDDC {} from org {}'.format(self.sddc_id, print('\n# Example: Delete SDDC {} from org {}'.format(
self.org_id)) self.sddc_id, self.org_id))
try: try:
task = self.vmc_client.orgs.Sddcs.delete(org=self.org_id, task = self.vmc_client.orgs.Sddcs.delete(
sddc=self.sddc_id) org=self.org_id, sddc=self.sddc_id)
except InvalidRequest as e: except InvalidRequest as e:
# Convert InvalidRequest to ErrorResponse to get error message # Convert InvalidRequest to ErrorResponse to get error message
error_response = e.data.convert_to(ErrorResponse) error_response = e.data.convert_to(ErrorResponse)
raise Exception(error_response.error_messages) raise Exception(error_response.error_messages)
wait_for_task(task_client=self.vmc_client.orgs.Tasks, wait_for_task(
task_client=self.vmc_client.orgs.Tasks,
org_id=self.org_id, org_id=self.org_id,
task_id=task.id, task_id=task.id,
interval_sec=self.interval_sec) interval_sec=self.interval_sec)
print('\n# Example: Remaining SDDCs:'.format(self.org_id)) print('\n# Example: Remaining SDDCs:')
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id) sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
self.print_output(sddcs) self.print_output(sddcs)
@ -170,10 +185,9 @@ class CreateDeleteSDDC(object):
self.print_output(sddcs) self.print_output(sddcs)
def print_output(self, sddcs): def print_output(self, sddcs):
table = []
for sddc in sddcs: for sddc in sddcs:
table.append([sddc.id, sddc.name, sddc.resource_config.region]) print('ID: {}, Name: {}, AWS Region: {}'.format(
print(tabulate(table, ['ID', 'Name', 'AWS Region'])) sddc.id, sddc.name, sddc.resource_config.region))
def get_subnet_id(self, vpc_map): def get_subnet_id(self, vpc_map):
for v in vpc_map.values(): for v in vpc_map.values():

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017. All Rights Reserved.
@ -17,7 +16,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.7+' __vcenter_version__ = '6.7+'
from tabulate import tabulate
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common import vapiconnect from samples.vsphere.common import vapiconnect
@ -28,8 +26,7 @@ class BackupJobList(object):
""" """
Demonstrates backup job list operation Demonstrates backup job list operation
Retrieves backup job details from vCenter and prints the data in Retrieves backup job details from vCenter and prints the data
tabular format
Prerequisites: Prerequisites:
- vCenter - vCenter
@ -55,16 +52,12 @@ class BackupJobList(object):
details_client = Details(self.stub_config) details_client = Details(self.stub_config)
job_list = details_client.list() job_list = details_client.list()
table = []
for info in job_list.values(): for info in job_list.values():
row = [info.start_time.strftime("%b %d %Y %H:%M"), print(
info.duration, 'Start time: {}, Duration: {}, Type: {}, Status: {}, Location: {}'
info.type, .format(
info.status, info.start_time.strftime("%b %d %Y %H:%M"), info.duration,
info.location] info.type, info.status, info.location))
table.append(row)
headers = ["Start time", "Duration", "Type", "Status", "Location"]
print(tabulate(table, headers))
def main(): def main():

View File

@ -1,8 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -17,11 +16,9 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.7+' __vcenter_version__ = '6.7+'
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common import vapiconnect from samples.vsphere.common import vapiconnect
from tabulate import tabulate
from com.vmware.appliance.recovery.backup_client import Schedules from com.vmware.appliance.recovery.backup_client import Schedules
@ -51,15 +48,19 @@ class BackupSchedule(object):
def setup(self): def setup(self):
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
parser.add_argument('-location', '--location', parser.add_argument(
'-location',
'--location',
required=True, required=True,
action='store', action='store',
help='URL of the backup location') help='URL of the backup location')
parser.add_argument('--location_user', parser.add_argument(
'--location_user',
required=True, required=True,
action='store', action='store',
help='Username for the given location') help='Username for the given location')
parser.add_argument('--location_password', parser.add_argument(
'--location_password',
required=True, required=True,
action='store', action='store',
help='Password for the given location') help='Password for the given location')
@ -98,9 +99,7 @@ class BackupSchedule(object):
def create_schedule(self): def create_schedule(self):
retention_info = Schedules.RetentionInfo(self.max_count) retention_info = Schedules.RetentionInfo(self.max_count)
recurrence_info = Schedules.RecurrenceInfo( recurrence_info = Schedules.RecurrenceInfo(
days=self.days, days=self.days, hour=self.hour, minute=self.minute)
hour=self.hour,
minute=self.minute)
create_spec = Schedules.CreateSpec( create_spec = Schedules.CreateSpec(
location=self.location, location=self.location,
location_user=self.location_user, location_user=self.location_user,
@ -113,9 +112,7 @@ class BackupSchedule(object):
def update_schedule(self): def update_schedule(self):
retention_info = Schedules.RetentionInfo(self.max_count) retention_info = Schedules.RetentionInfo(self.max_count)
recurrence_info = Schedules.RecurrenceInfo( recurrence_info = Schedules.RecurrenceInfo(
days=self.days, days=self.days, hour=self.hour, minute=self.minute)
hour=self.hour,
minute=self.minute)
update_spec = Schedules.UpdateSpec( update_spec = Schedules.UpdateSpec(
location=self.location, location=self.location,
location_user=self.location_user, location_user=self.location_user,
@ -132,17 +129,13 @@ class BackupSchedule(object):
recurrence_info = schedule_spec.recurrence_info recurrence_info = schedule_spec.recurrence_info
retention_info = schedule_spec.retention_info retention_info = schedule_spec.retention_info
table = [] print('Schedule ID: {}, Time: {}, Days: {}, Retention: {}'.format(
data = [self._schedule_id, self._schedule_id, "{}:{}".format(recurrence_info.hour,
"{}:{}".format(recurrence_info.hour, recurrence_info.minute), recurrence_info.minute),
" ".join(recurrence_info.days), " ".join(recurrence_info.days), retention_info.max_count))
retention_info.max_count]
table.append(data)
headers = ["Schedule ID", "Time", "Days", "Retention"]
print(tabulate(table, headers))
def run_backup(self): def run_backup(self):
schedule_spec = self.schedule_client.run(self._schedule_id) self.schedule_client.run(self._schedule_id)
def delete_schedule(self): def delete_schedule(self):
self.schedule_client.delete(self._schedule_id) self.schedule_client.delete(self._schedule_id)

View File

@ -1,8 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017, 2018. All Rights Reserved. * Copyright (c) VMware, Inc. 2017, 2018, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -16,11 +15,9 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__vcenter_version__ = '6.7+' __vcenter_version__ = '6.7+'
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common import vapiconnect from samples.vsphere.common import vapiconnect
from tabulate import tabulate
from com.vmware.appliance.logging_client import Forwarding from com.vmware.appliance.logging_client import Forwarding
@ -45,15 +42,15 @@ class LogForwarding(object):
def setup(self): def setup(self):
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
parser.add_argument('--loghost', parser.add_argument(
required=True, '--loghost', required=True, action='store', help='The log host')
action='store', parser.add_argument(
help='The log host') '--port',
parser.add_argument('--port',
required=True, required=True,
action='store', action='store',
help='The log host port number') help='The log host port number')
parser.add_argument('--protocol', parser.add_argument(
'--protocol',
required=True, required=True,
action='store', action='store',
help='The log host protocol (TCP/UDP/TLS)') help='The log host protocol (TCP/UDP/TLS)')
@ -86,37 +83,35 @@ class LogForwarding(object):
self.update_log_forwarding() self.update_log_forwarding()
def set_log_forwarding(self): def set_log_forwarding(self):
log_forwarding_config = [Forwarding.Config(hostname=self.loghost, log_forwarding_config = [
port=self.port, Forwarding.Config(
protocol=self.protocol)] hostname=self.loghost, port=self.port, protocol=self.protocol)
]
self.log_forwarding_client.set(log_forwarding_config) self.log_forwarding_client.set(log_forwarding_config)
def get_log_forwarding(self): def get_log_forwarding(self):
configs = self.log_forwarding_client.get() configs = self.log_forwarding_client.get()
print("\nLog forwarding configurations:") for cfg in configs:
table = [[cfg.hostname, cfg.port, cfg.protocol] for cfg in configs] print('Loghost: {}, Port: {}, Protocol: {}'.format(
headers = ["Loghost", "Port", "Protocol"] cfg.hostname, cfg.port, cfg.protocol))
print(tabulate(table, headers))
def test_log_forwarding(self): def test_log_forwarding(self):
test_response = self.log_forwarding_client.test(True) test_response = self.log_forwarding_client.test(True)
print("\nLog forwarding test response:") print("\nLog forwarding test response:")
table = [[resp.hostname, for resp in test_response:
resp.state, print('Loghost: {}, State: {}, Message: {}'.format(
resp.message.default_message if resp.message else None] resp.hostname, resp.state,
for resp in test_response] resp.message.default_message if resp.message else None))
headers = ["Loghost", "State", "Message"]
print(tabulate(table, headers))
def update_log_forwarding(self): def update_log_forwarding(self):
# Read log forwarding configuration # Read log forwarding configuration
log_forwarding_config = self.log_forwarding_client.get() log_forwarding_config = self.log_forwarding_client.get()
# Delete the newly added configuration # Delete the newly added configuration
log_forwarding_config = list(filter( log_forwarding_config = list(
lambda cfg: cfg.hostname != self.loghost, filter(lambda cfg: cfg.hostname != self.loghost,
log_forwarding_config)) log_forwarding_config))
# Apply the modified log forwarding configuration # Apply the modified log forwarding configuration

View File

@ -1,8 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -17,8 +16,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2018 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2018 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.7+' __vcenter_version__ = '6.7+'
from tabulate import tabulate
from vmware.vapi.vsphere.client import create_vsphere_client from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.ssl_helper import get_unverified_session from samples.vsphere.common.ssl_helper import get_unverified_session
@ -47,23 +44,19 @@ class ListServices(object):
session = get_unverified_session() if args.skipverification else None session = get_unverified_session() if args.skipverification else None
# Connect to vSphere client # Connect to vSphere client
self.client = create_vsphere_client(server=args.server, self.client = create_vsphere_client(
server=args.server,
username=args.username, username=args.username,
password=args.password, password=args.password,
session=session) session=session)
def run(self): def run(self):
services_list = self.client.vcenter.services.Service.list_details() services_list = self.client.vcenter.services.Service.list_details()
table = []
for key, value in services_list.items(): for key, value in services_list.items():
row = [key, print(
value.name_key, 'Service Name: {}, Service Name Key: {}, Service Health: {}, Service Status: {}, Service Startup Type: {}'
value.health, ).format(key, value.name_key, value.health, value.state,
value.state, value.startup_type)
value.startup_type]
table.append(row)
headers = ["Service Name", "Service Name Key", "Service Health", "Service Status", "Service Startup Type"]
print(tabulate(table, headers))
def main(): def main():