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

Merge pull request #118 from tianhao64/master

Remove tabulate from the dependency list
This commit is contained in:
Tianhao He 2018-11-21 23:55:49 -08:00 committed by GitHub
commit e89c3fb5a2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 494 additions and 526 deletions

View File

@ -1,7 +1,6 @@
pyVmomi >= 6.7
suds ; python_version < '3'
suds-jurko ; python_version >= '3.0'
tabulate
vapi-client-bindings == 1.5.0
vmc-client-bindings
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
* *******************************************************
*
@ -14,7 +14,6 @@
__author__ = 'VMware, Inc.'
from time import sleep
from tabulate import tabulate
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))
return False
else:
print("Estimated time remaining: {} minutes".
format(task.estimated_remaining_minutes))
print("Estimated time remaining: {} minutes".format(
task.estimated_remaining_minutes))
sleep(interval_sec)
@ -56,9 +55,7 @@ def list_all_tasks(task_client, org_id):
:param org_id: organization id
"""
tasks = task_client.list(org_id)
headers = ['ID', 'Status', 'Progress', 'Started', 'User']
table = []
for task in tasks:
table.append([task.id, task.status, task.progress_percent,
task.start_time, task.user_name])
print(tabulate(table, headers))
print('ID: {}, Status: {}, Progress: {}, Started: {}, User: {}'.format(
task.id, task.status, task.progress_percent, task.start_time,
task.user_name))

View File

@ -16,8 +16,8 @@
__author__ = 'VMware, Inc.'
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
@ -162,9 +162,7 @@ class DNSCrud(object):
def print_output(self, dns):
# DNS IP address might be empty
ips = getattr(dns.forwarders, 'ip_address', [])
result = [[dns.name, ips]]
print(tabulate(result, ['Name', 'IP Addresses']))
print('Name: {}, IP Addresses: {}'.format(dns.name, ips))
def main():

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
"""
* *******************************************************
* 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.vmc.model_client import ErrorResponse
from six.moves.urllib import parse
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client
from vmware.vapi.vsphere.client import create_vsphere_client
@ -38,17 +36,17 @@ class ConnectTovSphereWithDefaultCredentials(object):
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument(
'-r',
'--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.')
parser.add_argument(
'-o', '--org-id', required=True, help='Organization identifier.')
parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.')
parser.add_argument(
'-s', '--sddc-id', required=True, help='Sddc Identifier.')
args = parser.parse_args()
self.refresh_token = args.refresh_token
@ -59,12 +57,14 @@ class ConnectTovSphereWithDefaultCredentials(object):
# Connect to VMware Cloud on AWS
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
orgs = vmc_client.Orgs.list()
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
try:
@ -78,18 +78,20 @@ class ConnectTovSphereWithDefaultCredentials(object):
# Connect to vSphere client using the initial cloud admin credentials.
# Please use the new credentials to login after you reset the default one.
vsphere_client = create_vsphere_client(server,
username=sddc.resource_config.cloud_username,
password=sddc.resource_config.cloud_password)
print("\n# Example: Successfully connect to vCenter at '{}'".format(server))
vsphere_client = create_vsphere_client(
server,
username=sddc.resource_config.cloud_username,
password=sddc.resource_config.cloud_password)
print("\n# Example: Successfully connect to vCenter at '{}'".format(
server))
# List VMs in the vSphere instance
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(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():

View File

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

View File

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

View File

@ -1,8 +1,7 @@
#!/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
* *******************************************************
*
@ -17,11 +16,9 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.7+'
from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common import vapiconnect
from tabulate import tabulate
from com.vmware.appliance.recovery.backup_client import Schedules
@ -51,18 +48,22 @@ class BackupSchedule(object):
def setup(self):
parser = sample_cli.build_arg_parser()
parser.add_argument('-location', '--location',
required=True,
action='store',
help='URL of the backup location')
parser.add_argument('--location_user',
required=True,
action='store',
help='Username for the given location')
parser.add_argument('--location_password',
required=True,
action='store',
help='Password for the given location')
parser.add_argument(
'-location',
'--location',
required=True,
action='store',
help='URL of the backup location')
parser.add_argument(
'--location_user',
required=True,
action='store',
help='Username for the given location')
parser.add_argument(
'--location_password',
required=True,
action='store',
help='Password for the given location')
args = sample_util.process_cli_args(parser.parse_args())
self.location = args.location
@ -71,10 +72,10 @@ class BackupSchedule(object):
# Connect to vAPI services
self.stub_config = vapiconnect.connect(
host=args.server,
user=args.username,
pwd=args.password,
skip_verification=args.skipverification)
host=args.server,
user=args.username,
pwd=args.password,
skip_verification=args.skipverification)
self.schedule_client = Schedules(self.stub_config)
@ -98,30 +99,26 @@ class BackupSchedule(object):
def create_schedule(self):
retention_info = Schedules.RetentionInfo(self.max_count)
recurrence_info = Schedules.RecurrenceInfo(
days=self.days,
hour=self.hour,
minute=self.minute)
days=self.days, hour=self.hour, minute=self.minute)
create_spec = Schedules.CreateSpec(
location=self.location,
location_user=self.location_user,
location_password=self.location_password,
recurrence_info=recurrence_info,
retention_info=retention_info)
location=self.location,
location_user=self.location_user,
location_password=self.location_password,
recurrence_info=recurrence_info,
retention_info=retention_info)
self.schedule_client.create(self._schedule_id, create_spec)
def update_schedule(self):
retention_info = Schedules.RetentionInfo(self.max_count)
recurrence_info = Schedules.RecurrenceInfo(
days=self.days,
hour=self.hour,
minute=self.minute)
days=self.days, hour=self.hour, minute=self.minute)
update_spec = Schedules.UpdateSpec(
location=self.location,
location_user=self.location_user,
location_password=self.location_password,
recurrence_info=recurrence_info,
retention_info=retention_info)
location=self.location,
location_user=self.location_user,
location_password=self.location_password,
recurrence_info=recurrence_info,
retention_info=retention_info)
self.schedule_client.update(self._schedule_id, update_spec)
@ -132,17 +129,13 @@ class BackupSchedule(object):
recurrence_info = schedule_spec.recurrence_info
retention_info = schedule_spec.retention_info
table = []
data = [self._schedule_id,
"{}:{}".format(recurrence_info.hour, recurrence_info.minute),
" ".join(recurrence_info.days),
retention_info.max_count]
table.append(data)
headers = ["Schedule ID", "Time", "Days", "Retention"]
print(tabulate(table, headers))
print('Schedule ID: {}, Time: {}, Days: {}, Retention: {}'.format(
self._schedule_id, "{}:{}".format(recurrence_info.hour,
recurrence_info.minute),
" ".join(recurrence_info.days), retention_info.max_count))
def run_backup(self):
schedule_spec = self.schedule_client.run(self._schedule_id)
self.schedule_client.run(self._schedule_id)
def delete_schedule(self):
self.schedule_client.delete(self._schedule_id)

View File

@ -1,8 +1,7 @@
#!/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
* *******************************************************
*
@ -16,11 +15,9 @@
__author__ = 'VMware, Inc.'
__vcenter_version__ = '6.7+'
from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common import vapiconnect
from tabulate import tabulate
from com.vmware.appliance.logging_client import Forwarding
@ -45,18 +42,18 @@ class LogForwarding(object):
def setup(self):
parser = sample_cli.build_arg_parser()
parser.add_argument('--loghost',
required=True,
action='store',
help='The log host')
parser.add_argument('--port',
required=True,
action='store',
help='The log host port number')
parser.add_argument('--protocol',
required=True,
action='store',
help='The log host protocol (TCP/UDP/TLS)')
parser.add_argument(
'--loghost', required=True, action='store', help='The log host')
parser.add_argument(
'--port',
required=True,
action='store',
help='The log host port number')
parser.add_argument(
'--protocol',
required=True,
action='store',
help='The log host protocol (TCP/UDP/TLS)')
args = sample_util.process_cli_args(parser.parse_args())
self.loghost = args.loghost
@ -65,10 +62,10 @@ class LogForwarding(object):
# Connect to vAPI services
self.stub_config = vapiconnect.connect(
host=args.server,
user=args.username,
pwd=args.password,
skip_verification=args.skipverification)
host=args.server,
user=args.username,
pwd=args.password,
skip_verification=args.skipverification)
self.log_forwarding_client = Forwarding(self.stub_config)
@ -86,38 +83,36 @@ class LogForwarding(object):
self.update_log_forwarding()
def set_log_forwarding(self):
log_forwarding_config = [Forwarding.Config(hostname=self.loghost,
port=self.port,
protocol=self.protocol)]
log_forwarding_config = [
Forwarding.Config(
hostname=self.loghost, port=self.port, protocol=self.protocol)
]
self.log_forwarding_client.set(log_forwarding_config)
def get_log_forwarding(self):
configs = self.log_forwarding_client.get()
print("\nLog forwarding configurations:")
table = [[cfg.hostname, cfg.port, cfg.protocol] for cfg in configs]
headers = ["Loghost", "Port", "Protocol"]
print(tabulate(table, headers))
for cfg in configs:
print('Loghost: {}, Port: {}, Protocol: {}'.format(
cfg.hostname, cfg.port, cfg.protocol))
def test_log_forwarding(self):
test_response = self.log_forwarding_client.test(True)
print("\nLog forwarding test response:")
table = [[resp.hostname,
resp.state,
resp.message.default_message if resp.message else None]
for resp in test_response]
headers = ["Loghost", "State", "Message"]
print(tabulate(table, headers))
for resp in test_response:
print('Loghost: {}, State: {}, Message: {}'.format(
resp.hostname, resp.state,
resp.message.default_message if resp.message else None))
def update_log_forwarding(self):
# Read log forwarding configuration
log_forwarding_config = self.log_forwarding_client.get()
# Delete the newly added configuration
log_forwarding_config = list(filter(
lambda cfg: cfg.hostname != self.loghost,
log_forwarding_config))
log_forwarding_config = list(
filter(lambda cfg: cfg.hostname != self.loghost,
log_forwarding_config))
# Apply the modified log forwarding configuration
self.log_forwarding_client.set(log_forwarding_config)

View File

@ -1,8 +1,7 @@
#!/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
* *******************************************************
*
@ -17,8 +16,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2018 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.7+'
from tabulate import tabulate
from vmware.vapi.vsphere.client import create_vsphere_client
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
# Connect to vSphere client
self.client = create_vsphere_client(server=args.server,
username=args.username,
password=args.password,
session=session)
self.client = create_vsphere_client(
server=args.server,
username=args.username,
password=args.password,
session=session)
def run(self):
services_list = self.client.vcenter.services.Service.list_details()
table = []
for key, value in services_list.items():
row = [key,
value.name_key,
value.health,
value.state,
value.startup_type]
table.append(row)
headers = ["Service Name", "Service Name Key", "Service Health", "Service Status", "Service Startup Type"]
print(tabulate(table, headers))
print(
'Service Name: {}, Service Name Key: {}, Service Health: {}, Service Status: {}, Service Startup Type: {}'
).format(key, value.name_key, value.health, value.state,
value.startup_type)
def main():