Ejemplo n.º 1
0
def main():
    '''Main routine.'''
    # check for single command argument
    if len(sys.argv) != 2:
        sys.exit('Usage: python ' + sys.argv[0] + ' rg_name')

    rgname = sys.argv[1]

    # if in Azure cloud shell, authenticate using the MSI endpoint
    if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ:
        access_token = azurerm.get_access_token_from_cli()
        subscription_id = azurerm.get_subscription_from_cli()
    else:  # load service principal details from a config file
        try:
            with open('azurermconfig.json') as configfile:
                configdata = json.load(configfile)
        except FileNotFoundError:
            sys.exit('Error: Expecting azurermconfig.json in current folder')

        tenant_id = configdata['tenantId']
        app_id = configdata['appId']
        app_secret = configdata['appSecret']
        subscription_id = configdata['subscriptionId']

        # authenticate
        access_token = azurerm.get_access_token(tenant_id, app_id, app_secret)

    # delete a resource group
    rgreturn = azurerm.delete_resource_group(access_token, subscription_id,
                                             rgname)
    print(rgreturn)
Ejemplo n.º 2
0
def main():
    '''Main routine.'''
    # if in Azure cloud shell, authenticate using the MSI endpoint
    if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ:
        access_token = azurerm.get_access_token_from_cli()
        subscription_id = azurerm.get_subscription_from_cli()
    else: # load service principal details from a config file        
        try:
            with open('azurermconfig.json') as configfile:
                configdata = json.load(configfile)
        except FileNotFoundError:
            sys.exit('Error: Expecting azurermconfig.json in current folder')

        tenant_id = configdata['tenantId']
        app_id = configdata['appId']
        app_secret = configdata['appSecret']
        subscription_id = configdata['subscriptionId']

        # authenticate
        access_token = azurerm.get_access_token(tenant_id, app_id, app_secret)

    # list resource groups
    resource_groups = azurerm.list_resource_groups(access_token, subscription_id)
    for rgname in resource_groups['value']:
        print(rgname['name'] + ', ' + rgname['location'])
        '''
Ejemplo n.º 3
0
def main():
    '''Main routine.'''
    # validate command line arguments
    arg_parser = argparse.ArgumentParser()

    arg_parser.add_argument('--uri',
                            '-u',
                            required=True,
                            action='store',
                            help='Template URI')
    arg_parser.add_argument('--params',
                            '-p',
                            required=True,
                            action='store',
                            help='Parameters json file')
    arg_parser.add_argument('--rg',
                            '-g',
                            required=True,
                            action='store',
                            help='Resource Group name')
    arg_parser.add_argument('--sub',
                            '-s',
                            required=False,
                            action='store',
                            help='subscription id (optional)')

    args = arg_parser.parse_args()

    template_uri = args.uri
    params = args.params
    rgname = args.rg
    subscription_id = args.sub

    # load parameters file
    try:
        with open(params) as params_file:
            param_data = json.load(params_file)
    except FileNotFoundError:
        print('Error: Expecting ' + params + ' in current folder')
        sys.exit()

    access_token = azurerm.get_access_token_from_cli()
    if subscription_id is None:
        subscription_id = azurerm.get_subscription_from_cli()
    deployment_name = Haikunator().haikunate()
    print('Deployment name:' + deployment_name)

    deploy_return = azurerm.deploy_template_uri(access_token, subscription_id,
                                                rgname, deployment_name,
                                                template_uri, param_data)

    print(
        json.dumps(deploy_return.json(),
                   sort_keys=False,
                   indent=2,
                   separators=(',', ': ')))
Ejemplo n.º 4
0
def main():
    '''Main routine.'''
    # validate command line arguments
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('--vmssname',
                            '-n',
                            required=True,
                            action='store',
                            help='VMSS Name')
    arg_parser.add_argument('--rgname',
                            '-g',
                            required=True,
                            action='store',
                            help='Resource Group Name')
    arg_parser.add_argument('--details',
                            '-a',
                            required=False,
                            action='store_true',
                            default=False,
                            help='Print all details')
    args = arg_parser.parse_args()

    name = args.vmssname
    rgname = args.rgname
    details = args.details

    # authenticate
    access_token = azurerm.get_access_token_from_cli()
    subscription_id = azurerm.get_subscription_from_cli()

    # get rolling upgrade latest status
    upgrade_status = azurerm.get_vmss_rolling_upgrades(access_token,
                                                       subscription_id, rgname,
                                                       name)

    # print details
    if details is True:
        print(
            json.dumps(upgrade_status,
                       sort_keys=False,
                       indent=2,
                       separators=(',', ': ')))
    else:
        print(
            json.dumps(upgrade_status,
                       sort_keys=False,
                       indent=2,
                       separators=(',', ': ')))
Ejemplo n.º 5
0
import string,random,time,azurerm,json
from azure.storage.table import TableService, Entity

# Define variables to handle Azure authentication
auth_token = azurerm.get_access_token_from_cli()
subscription_id = azurerm.get_subscription_from_cli()

# Define variables with random resource group and storage account names
resourcegroup_name = 'kev'+''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6))
storageaccount_name = 'kev'+''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6))
location = 'southcentralus'

###
# Create the a resource group for our demo
# We need a resource group and a storage account. A random name is generated, as each storage account name must be globally unique.
###
response = azurerm.create_resource_group(auth_token, subscription_id, resourcegroup_name, location)
if response.status_code == 200 or response.status_code == 201:
    print('Resource group: ' + resourcegroup_name + ' created successfully.')
else:
    print('Error creating resource group')

# Create a storage account for our demo
response = azurerm.create_storage_account(auth_token, subscription_id, resourcegroup_name, storageaccount_name,  location, storage_type='Standard_LRS')
if response.status_code == 202:
    print('Storage account: ' + storageaccount_name + ' created successfully.')
    time.sleep(2)
else:
    print('Error creating storage account')

Ejemplo n.º 6
0
def main():
    '''Main routine.'''
    # validate command line arguments
    arg_parser = argparse.ArgumentParser()

    arg_parser.add_argument('--add',
                            '-a',
                            action='store_true',
                            default=False,
                            help='add a key vault')
    arg_parser.add_argument('--delete',
                            '-d',
                            action='store_true',
                            default=False,
                            help='delete a key vault')
    arg_parser.add_argument('--name',
                            '-n',
                            required=True,
                            action='store',
                            help='Name')
    arg_parser.add_argument('--rgname',
                            '-g',
                            required=True,
                            action='store',
                            help='Resource Group Name')
    arg_parser.add_argument('--location',
                            '-l',
                            required=True,
                            action='store',
                            help='Location, e.g. eastus')
    arg_parser.add_argument('--verbose',
                            '-v',
                            action='store_true',
                            default=False,
                            help='Print operational details')

    args = arg_parser.parse_args()
    name = args.name
    rgname = args.rgname
    location = args.location

    if args.add is True and args.delete is True:
        sys.exit('Specify --add or --delete, not both.')
    if args.add is False and args.delete is False:
        sys.exit('No operation specified, use --add or --delete.')

    if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ:
        endpoint = os.environ['MSI_ENDPOINT']
    else:
        sys.exit('Not running in cloud shell or MSI_ENDPOINT not set')

    # get Azure auth token
    if args.verbose is True:
        print('Getting Azure token from MSI endpoint..')

    access_token = azurerm.get_access_token_from_cli()

    if args.verbose is True:
        print('Getting Azure subscription ID from MSI endpoint..')
    subscription_id = azurerm.get_subscription_from_cli()

    # execute specified operation
    if args.add is True:  # create a key vault
        # get Azure tenant ID
        if args.verbose is True:
            print('Getting list of tenant IDs...')
        tenants = azurerm.list_tenants(access_token)
        tenant_id = tenants['value'][0]['tenantId']
        if args.verbose is True:
            print('My tenantId = ' + tenant_id)

        # get Graph object ID
        if args.verbose is True:
            print('Querying graph...')
        object_id = azurerm.get_object_id_from_graph()
        if args.verbose is True:
            print('My object ID = ' + object_id)

        # create key vault
        ret = azurerm.create_keyvault(access_token,
                                      subscription_id,
                                      rgname,
                                      name,
                                      location,
                                      tenant_id=tenant_id,
                                      object_id=object_id)
        if ret.status_code == 200:
            print('Successsfully created key vault: ' + name)
            print('Vault URI: ' + ret.json()['properties']['vaultUri'])
        else:
            print('Return code ' + str(ret.status_code) +
                  ' from create_keyvault().')
            print(ret.text)

    # else delete named key vault
    else:
        ret = azurerm.delete_keyvault(access_token, subscription_id, rgname,
                                      name)
        if ret.status_code == 200:
            print('Successsfully deleted key vault: ' + name)
        else:
            print('Return code ' + str(ret.status_code) +
                  ' from delete_keyvault().')
            print(ret.text)
Ejemplo n.º 7
0
def main():
    '''Main routine.'''
    # validate command line arguments
    arg_parser = argparse.ArgumentParser()

    arg_parser.add_argument('--vmssname',
                            '-n',
                            required=True,
                            action='store',
                            help='Scale set name')
    arg_parser.add_argument('--rgname',
                            '-g',
                            required=True,
                            action='store',
                            help='Resource Group Name')
    arg_parser.add_argument('--operation',
                            '-o',
                            required=True,
                            action='store',
                            help='Operation (attach/detach)')
    arg_parser.add_argument('--vmid',
                            '-i',
                            required=True,
                            action='store',
                            help='VM id')
    arg_parser.add_argument('--lun',
                            '-l',
                            required=True,
                            action='store',
                            help='lun id')
    arg_parser.add_argument('--diskname',
                            '-d',
                            required=False,
                            action='store',
                            help='Optional password')

    args = arg_parser.parse_args()
    vmssname = args.vmssname
    rgname = args.rgname
    operation = args.operation
    vmid = args.vmid
    lun = int(args.lun)
    diskname = args.diskname

    if operation != 'attach' and operation != 'detach':
        sys.exit('--operation must be attach or detach')
    if diskname is None and operation == 'attach':
        sys.exit('--diskname is required for attach operation.')

    subscription_id = azurerm.get_subscription_from_cli()

    # authenticate
    access_token = azurerm.get_access_token_from_cli()

    # do a get on the VM
    vmssvm_model = azurerm.get_vmss_vm(access_token, subscription_id, rgname,
                                       vmssname, vmid)

    # check operation
    if operation == 'attach':
        new_model = attach_model(subscription_id, rgname, vmssvm_model,
                                 diskname, lun)
    else:
        if operation == 'detach':
            new_model = detach_model(vmssvm_model, lun)

    # do a put on the VM
    rmreturn = azurerm.put_vmss_vm(access_token, subscription_id, rgname,
                                   vmssname, vmid, new_model)

    if rmreturn.status_code != 201:
        sys.exit('Error ' + str(rmreturn.status_code) + ' creating VM. ' +
                 rmreturn.text)

    print(
        json.dumps(rmreturn, sort_keys=False, indent=2,
                   separators=(',', ': ')))