repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
_delete_resource
|
python
|
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
|
Delete a generic Elasticache resource.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L123-L175
| null |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
describe_cache_clusters
|
python
|
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
|
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L284-L298
|
[
"def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,\n region=None, key=None, keyid=None, profile=None, **args):\n if conn is None:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n func = 'describe_'+res_type+'s'\n f = getattr(conn, func)\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n # Undocumented, but you can't pass 'Marker' if searching for a specific resource...\n args.update({name_param: name} if name else {'Marker': ''})\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n return _collect_results(f, info_node, args)\n except botocore.exceptions.ClientError as e:\n log.debug(e)\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
cache_cluster_exists
|
python
|
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
|
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L301-L311
|
[
"def describe_cache_clusters(name=None, conn=None, region=None, key=None,\n keyid=None, profile=None, **args):\n '''\n Return details about all (or just one) Elasticache cache clusters.\n\n Example:\n\n .. code-block:: bash\n\n salt myminion boto3_elasticache.describe_cache_clusters\n salt myminion boto3_elasticache.describe_cache_clusters myelasticache\n '''\n return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',\n info_node='CacheClusters', conn=conn, region=region, key=key,\n keyid=keyid, profile=profile, **args)\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
create_cache_cluster
|
python
|
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L314-L341
|
[
"def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,\n status_good='available', region=None, key=None, keyid=None, profile=None,\n **args):\n try:\n wait = int(wait)\n except Exception:\n raise SaltInvocationError(\"Bad value ('{0}') passed for 'wait' param - must be an \"\n \"int or boolean.\".format(wait))\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if name_param in args:\n log.info(\n \"'name: %s' param being overridden by explicitly provided '%s: %s'\",\n name, name_param, args[name_param]\n )\n name = args[name_param]\n else:\n args[name_param] = name\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n func = 'create_'+res_type\n f = getattr(conn, func)\n if wait:\n func = 'describe_'+res_type+'s'\n s = globals()[func]\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n try:\n f(**args)\n if not wait:\n log.info('%s %s created.', desc.title(), name)\n return True\n log.info('Waiting up to %s seconds for %s %s to be become available.',\n wait, desc, name)\n orig_wait = wait\n while wait > 0:\n r = s(name=name, conn=conn)\n if r and r[0].get(status_param) == status_good:\n log.info('%s %s created and available.', desc.title(), name)\n return True\n sleep = wait if wait % 60 == wait else 60\n log.info('Sleeping %s seconds for %s %s to become available.',\n sleep, desc, name)\n time.sleep(sleep)\n wait -= sleep\n log.error('%s %s not available after %s seconds!',\n desc.title(), name, orig_wait)\n return False\n except botocore.exceptions.ClientError as e:\n msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)\n log.error(msg)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
replication_group_exists
|
python
|
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
|
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L411-L422
|
[
"def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):\n '''\n Return details about all (or just one) Elasticache replication groups.\n\n Example:\n\n .. code-block:: bash\n\n salt myminion boto3_elasticache.describe_replication_groups\n salt myminion boto3_elasticache.describe_replication_groups myelasticache\n '''\n return _describe_resource(name=name, name_param='ReplicationGroupId',\n res_type='replication_group', info_node='ReplicationGroups',\n conn=conn, region=region, key=key, keyid=keyid, profile=profile)\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
delete_replication_group
|
python
|
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L482-L494
|
[
"def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,\n status_gone='deleted', region=None, key=None, keyid=None, profile=None,\n **args):\n '''\n Delete a generic Elasticache resource.\n '''\n try:\n wait = int(wait)\n except Exception:\n raise SaltInvocationError(\"Bad value ('{0}') passed for 'wait' param - must be an \"\n \"int or boolean.\".format(wait))\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if name_param in args:\n log.info(\n \"'name: %s' param being overridden by explicitly provided '%s: %s'\",\n name, name_param, args[name_param]\n )\n name = args[name_param]\n else:\n args[name_param] = name\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n func = 'delete_'+res_type\n f = getattr(conn, func)\n if wait:\n func = 'describe_'+res_type+'s'\n s = globals()[func]\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n try:\n\n f(**args)\n if not wait:\n log.info('%s %s deletion requested.', desc.title(), name)\n return True\n log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)\n orig_wait = wait\n while wait > 0:\n r = s(name=name, conn=conn)\n if not r or r[0].get(status_param) == status_gone:\n log.info('%s %s deleted.', desc.title(), name)\n return True\n sleep = wait if wait % 60 == wait else 60\n log.info('Sleeping %s seconds for %s %s to be deleted.',\n sleep, desc, name)\n time.sleep(sleep)\n wait -= sleep\n log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)\n\n return False\n except botocore.exceptions.ClientError as e:\n log.error('Failed to delete %s %s: %s', desc, name, e)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
cache_subnet_group_exists
|
python
|
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
|
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L512-L522
|
[
"def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):\n '''\n Return details about all (or just one) Elasticache replication groups.\n\n Example:\n\n .. code-block:: bash\n\n salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1\n '''\n return _describe_resource(name=name, name_param='CacheSubnetGroupName',\n res_type='cache_subnet_group', info_node='CacheSubnetGroups',\n conn=conn, region=region, key=key, keyid=keyid, profile=profile)\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
list_cache_subnet_groups
|
python
|
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
|
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L525-L536
|
[
"def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):\n '''\n Return details about all (or just one) Elasticache replication groups.\n\n Example:\n\n .. code-block:: bash\n\n salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1\n '''\n return _describe_resource(name=name, name_param='CacheSubnetGroupName',\n res_type='cache_subnet_group', info_node='CacheSubnetGroups',\n conn=conn, region=region, key=key, keyid=keyid, profile=profile)\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
create_cache_subnet_group
|
python
|
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L539-L574
|
[
"def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,\n status_good='available', region=None, key=None, keyid=None, profile=None,\n **args):\n try:\n wait = int(wait)\n except Exception:\n raise SaltInvocationError(\"Bad value ('{0}') passed for 'wait' param - must be an \"\n \"int or boolean.\".format(wait))\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if name_param in args:\n log.info(\n \"'name: %s' param being overridden by explicitly provided '%s: %s'\",\n name, name_param, args[name_param]\n )\n name = args[name_param]\n else:\n args[name_param] = name\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n func = 'create_'+res_type\n f = getattr(conn, func)\n if wait:\n func = 'describe_'+res_type+'s'\n s = globals()[func]\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n try:\n f(**args)\n if not wait:\n log.info('%s %s created.', desc.title(), name)\n return True\n log.info('Waiting up to %s seconds for %s %s to be become available.',\n wait, desc, name)\n orig_wait = wait\n while wait > 0:\n r = s(name=name, conn=conn)\n if r and r[0].get(status_param) == status_good:\n log.info('%s %s created and available.', desc.title(), name)\n return True\n sleep = wait if wait % 60 == wait else 60\n log.info('Sleeping %s seconds for %s %s to become available.',\n sleep, desc, name)\n time.sleep(sleep)\n wait -= sleep\n log.error('%s %s not available after %s seconds!',\n desc.title(), name, orig_wait)\n return False\n except botocore.exceptions.ClientError as e:\n msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)\n log.error(msg)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
cache_security_group_exists
|
python
|
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
|
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L646-L657
|
[
"def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):\n '''\n Return details about all (or just one) Elasticache cache clusters.\n\n Example:\n\n .. code-block:: bash\n\n salt myminion boto3_elasticache.describe_cache_security_groups\n salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp\n '''\n return _describe_resource(name=name, name_param='CacheSecurityGroupName',\n res_type='cache_security_group', info_node='CacheSecurityGroups',\n conn=conn, region=region, key=key, keyid=keyid, profile=profile)\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
create_cache_security_group
|
python
|
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L660-L672
|
[
"def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,\n status_good='available', region=None, key=None, keyid=None, profile=None,\n **args):\n try:\n wait = int(wait)\n except Exception:\n raise SaltInvocationError(\"Bad value ('{0}') passed for 'wait' param - must be an \"\n \"int or boolean.\".format(wait))\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if name_param in args:\n log.info(\n \"'name: %s' param being overridden by explicitly provided '%s: %s'\",\n name, name_param, args[name_param]\n )\n name = args[name_param]\n else:\n args[name_param] = name\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n func = 'create_'+res_type\n f = getattr(conn, func)\n if wait:\n func = 'describe_'+res_type+'s'\n s = globals()[func]\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n try:\n f(**args)\n if not wait:\n log.info('%s %s created.', desc.title(), name)\n return True\n log.info('Waiting up to %s seconds for %s %s to be become available.',\n wait, desc, name)\n orig_wait = wait\n while wait > 0:\n r = s(name=name, conn=conn)\n if r and r[0].get(status_param) == status_good:\n log.info('%s %s created and available.', desc.title(), name)\n return True\n sleep = wait if wait % 60 == wait else 60\n log.info('Sleeping %s seconds for %s %s to become available.',\n sleep, desc, name)\n time.sleep(sleep)\n wait -= sleep\n log.error('%s %s not available after %s seconds!',\n desc.title(), name, orig_wait)\n return False\n except botocore.exceptions.ClientError as e:\n msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)\n log.error(msg)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
delete_cache_security_group
|
python
|
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L675-L687
|
[
"def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,\n status_gone='deleted', region=None, key=None, keyid=None, profile=None,\n **args):\n '''\n Delete a generic Elasticache resource.\n '''\n try:\n wait = int(wait)\n except Exception:\n raise SaltInvocationError(\"Bad value ('{0}') passed for 'wait' param - must be an \"\n \"int or boolean.\".format(wait))\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if name_param in args:\n log.info(\n \"'name: %s' param being overridden by explicitly provided '%s: %s'\",\n name, name_param, args[name_param]\n )\n name = args[name_param]\n else:\n args[name_param] = name\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n func = 'delete_'+res_type\n f = getattr(conn, func)\n if wait:\n func = 'describe_'+res_type+'s'\n s = globals()[func]\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n try:\n\n f(**args)\n if not wait:\n log.info('%s %s deletion requested.', desc.title(), name)\n return True\n log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)\n orig_wait = wait\n while wait > 0:\n r = s(name=name, conn=conn)\n if not r or r[0].get(status_param) == status_gone:\n log.info('%s %s deleted.', desc.title(), name)\n return True\n sleep = wait if wait % 60 == wait else 60\n log.info('Sleeping %s seconds for %s %s to be deleted.',\n sleep, desc, name)\n time.sleep(sleep)\n wait -= sleep\n log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)\n\n return False\n except botocore.exceptions.ClientError as e:\n log.error('Failed to delete %s %s: %s', desc, name, e)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
authorize_cache_security_group_ingress
|
python
|
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
|
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L690-L721
| null |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
describe_cache_parameter_groups
|
python
|
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
|
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L903-L917
|
[
"def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,\n region=None, key=None, keyid=None, profile=None, **args):\n if conn is None:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n func = 'describe_'+res_type+'s'\n f = getattr(conn, func)\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n # Undocumented, but you can't pass 'Marker' if searching for a specific resource...\n args.update({name_param: name} if name else {'Marker': ''})\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n return _collect_results(f, info_node, args)\n except botocore.exceptions.ClientError as e:\n log.debug(e)\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
describe_cache_parameters
|
python
|
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
|
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L920-L956
|
[
"def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,\n region=None, key=None, keyid=None, profile=None, **args):\n if conn is None:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n func = 'describe_'+res_type+'s'\n f = getattr(conn, func)\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n # Undocumented, but you can't pass 'Marker' if searching for a specific resource...\n args.update({name_param: name} if name else {'Marker': ''})\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n return _collect_results(f, info_node, args)\n except botocore.exceptions.ClientError as e:\n log.debug(e)\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/boto3_elasticache.py
|
modify_cache_parameter_group
|
python
|
def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,
**args):
'''
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
'''
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args):
return False
return True
|
Update a cache parameter group in place.
Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20
params may be modified in one underlying boto call. This means that if more than 20 params
need to be changed, the update is performed in blocks of 20, which in turns means that if a
later sub-call fails after an earlier one has succeeded, the overall update will be left
partially applied.
CacheParameterGroupName
The name of the cache parameter group to modify.
ParameterNameValues
A [list] of {dicts}, each composed of a parameter name and a value, for the parameter
update. At least one parameter/value pair is required.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_parameter_group \
CacheParameterGroupName=myParamGroup \
ParameterNameValues='[ { ParameterName: timeout,
ParameterValue: "30" },
{ ParameterName: appendonly,
ParameterValue: "yes" } ]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L977-L1028
|
[
"def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,\n status_good='available', region=None, key=None, keyid=None, profile=None,\n **args):\n try:\n wait = int(wait)\n except Exception:\n raise SaltInvocationError(\"Bad value ('{0}') passed for 'wait' param - must be an \"\n \"int or boolean.\".format(wait))\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if name_param in args:\n log.info(\n \"'name: %s' param being overridden by explicitly provided '%s: %s'\",\n name, name_param, args[name_param]\n )\n name = args[name_param]\n else:\n args[name_param] = name\n args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n try:\n func = 'modify_'+res_type\n f = getattr(conn, func)\n if wait:\n func = 'describe_'+res_type+'s'\n s = globals()[func]\n except (AttributeError, KeyError) as e:\n raise SaltInvocationError(\"No function '{0}()' found: {1}\".format(func, e.message))\n try:\n f(**args)\n if not wait:\n log.info('%s %s modification requested.', desc.title(), name)\n return True\n log.info('Waiting up to %s seconds for %s %s to be become available.',\n wait, desc, name)\n orig_wait = wait\n while wait > 0:\n r = s(name=name, conn=conn)\n if r and r[0].get(status_param) == status_good:\n log.info('%s %s modified and available.', desc.title(), name)\n return True\n sleep = wait if wait % 60 == wait else 60\n log.info('Sleeping %s seconds for %s %s to become available.',\n sleep, desc, name)\n time.sleep(sleep)\n wait -= sleep\n log.error('%s %s not available after %s seconds!',\n desc.title(), name, orig_wait)\n return False\n except botocore.exceptions.ClientError as e:\n msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)\n log.error(msg)\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Execution module for Amazon Elasticache using boto3
===================================================
.. versionadded:: 2017.7.0
:configuration: This module accepts explicit elasticache credentials but can
also utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H
elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
elasticache.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# keep lint from whinging about perfectly valid code...
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
from salt.exceptions import SaltInvocationError, CommandExecutionError
import salt.utils.compat
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
try:
#pylint: disable=unused-import
import botocore
import boto3
#pylint: enable=unused-import
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs()
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO3:
__utils__['boto3.assign_funcs'](__name__, 'elasticache',
get_conn_funcname='_get_conn',
cache_id_funcname='_cache_id',
exactly_one_funcname=None)
def _collect_results(func, item, args, marker='Marker'):
ret = []
Marker = args[marker] if marker in args else ''
while Marker is not None:
r = func(**args)
ret += r.get(item)
Marker = r.get(marker)
args.update({marker: Marker})
return ret
def _describe_resource(name=None, name_param=None, res_type=None, info_node=None, conn=None,
region=None, key=None, keyid=None, profile=None, **args):
if conn is None:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
func = 'describe_'+res_type+'s'
f = getattr(conn, func)
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
# Undocumented, but you can't pass 'Marker' if searching for a specific resource...
args.update({name_param: name} if name else {'Marker': ''})
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
return _collect_results(f, info_node, args)
except botocore.exceptions.ClientError as e:
log.debug(e)
return None
def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None,
status_gone='deleted', region=None, key=None, keyid=None, profile=None,
**args):
'''
Delete a generic Elasticache resource.
'''
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'delete_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s deletion requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be deleted.', wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to be deleted.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not deleted after %s seconds!', desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
log.error('Failed to delete %s %s: %s', desc, name, e)
return False
def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'create_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s created.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s created and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to create {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, status_param=None,
status_good='available', region=None, key=None, keyid=None, profile=None,
**args):
try:
wait = int(wait)
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name_param in args:
log.info(
"'name: %s' param being overridden by explicitly provided '%s: %s'",
name, name_param, args[name_param]
)
name = args[name_param]
else:
args[name_param] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
func = 'modify_'+res_type
f = getattr(conn, func)
if wait:
func = 'describe_'+res_type+'s'
s = globals()[func]
except (AttributeError, KeyError) as e:
raise SaltInvocationError("No function '{0}()' found: {1}".format(func, e.message))
try:
f(**args)
if not wait:
log.info('%s %s modification requested.', desc.title(), name)
return True
log.info('Waiting up to %s seconds for %s %s to be become available.',
wait, desc, name)
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if r and r[0].get(status_param) == status_good:
log.info('%s %s modified and available.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
log.info('Sleeping %s seconds for %s %s to become available.',
sleep, desc, name)
time.sleep(sleep)
wait -= sleep
log.error('%s %s not available after %s seconds!',
desc.title(), name, orig_wait)
return False
except botocore.exceptions.ClientError as e:
msg = 'Failed to modify {0} {1}: {2}'.format(desc, name, e)
log.error(msg)
return False
def describe_cache_clusters(name=None, conn=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_clusters
salt myminion boto3_elasticache.describe_cache_clusters myelasticache
'''
return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster',
info_node='CacheClusters', conn=conn, region=region, key=key,
keyid=keyid, profile=profile, **args)
def cache_cluster_exists(name, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a cache cluster exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_cluster_exists myelasticache
'''
return bool(describe_cache_clusters(name=name, conn=conn, region=region, key=key, keyid=keyid, profile=profile))
def create_cache_cluster(name, wait=600, security_groups=None,
region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
Engine=redis \
CacheNodeType=cache.t2.micro \
NumCacheNodes=1 \
SecurityGroupIds='[sg-11223344]' \
CacheSubnetGroupName=myCacheSubnetGroup
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_cluster(name, wait=600, security_groups=None, region=None,
key=None, keyid=None, profile=None, **args):
'''
Update a cache cluster in place.
Notes: {ApplyImmediately: False} is pretty danged silly in the context of salt.
You can pass it, but for fairly obvious reasons the results over multiple
runs will be undefined and probably contrary to your desired state.
Reducing the number of nodes requires an EXPLICIT CacheNodeIdsToRemove be
passed, which until a reasonable heuristic for programmatically deciding
which nodes to remove has been established, MUST be decided and populated
intentionally before a state call, and removed again before the next. In
practice this is not particularly useful and should probably be avoided.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_cluster name=myCacheCluster \
NotificationTopicStatus=inactive
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_cluster(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache cluster.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete myelasticache
'''
return _delete_resource(name, name_param='CacheClusterId', desc='cache cluster',
res_type='cache_cluster', wait=wait,
status_param='CacheClusterStatus',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_replication_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_replication_groups
salt myminion boto3_elasticache.describe_replication_groups myelasticache
'''
return _describe_resource(name=name, name_param='ReplicationGroupId',
res_type='replication_group', info_node='ReplicationGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.replication_group_exists myelasticache
'''
return bool(describe_replication_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Create a replication group.
Params are extensive and variable - see
http://boto3.readthedocs.io/en/latest/reference/services/elasticache.html?#ElastiCache.Client.create_replication_group
for in-depth usage documentation.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_replication_group \
name=myelasticache \
ReplicationGroupDescription=description
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_replication_group(name, wait=600, security_groups=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Modify a replication group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_replication_group \
name=myelasticache \
ReplicationGroupDescription=newDescription
'''
if security_groups:
if not isinstance(security_groups, list):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region,
key=key, keyid=keyid, profile=profile)
if 'SecurityGroupIds' not in args:
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_replication_group(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache replication group, optionally taking a snapshot first.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_replication_group my-replication-group
'''
return _delete_resource(name, name_param='ReplicationGroupId', desc='replication group',
res_type='replication_group', wait=wait, status_param='Status',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_subnet_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache replication groups.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_subnet_groups region=us-east-1
'''
return _describe_resource(name=name, name_param='CacheSubnetGroupName',
res_type='cache_subnet_group', info_node='CacheSubnetGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_subnet_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache subnet group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_subnet_group_exists my-subnet-group
'''
return bool(describe_cache_subnet_groups(name=name, region=region, key=key, keyid=keyid, profile=profile))
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
describe_cache_subnet_groups(None, region, key, keyid, profile)]
def create_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Create an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_subnet_group name=my-subnet-group \
CacheSubnetGroupDescription="description" \
subnets='[myVPCSubnet1,myVPCSubnet2]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
if subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught further down if incorrect.
args['SubnetIds'] += [subnet]
continue
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet, region=region, key=key,
keyid=keyid, profile=profile).get('subnets')
if not sn:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _create_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def modify_cache_subnet_group(name, subnets=None, region=None, key=None, keyid=None, profile=None, **args):
'''
Modify an ElastiCache subnet group
Example:
.. code-block:: bash
salt myminion boto3_elasticache.modify_cache_subnet_group \
name=my-subnet-group \
subnets='[myVPCSubnet3]'
'''
if subnets:
if 'SubnetIds' not in args:
args['SubnetIds'] = []
if not isinstance(subnets, list):
subnets = [subnets]
for subnet in subnets:
sn = __salt__['boto_vpc.describe_subnets'](subnet_names=subnet,
region=region, key=key, keyid=keyid,
profile=profile).get('subnets')
if len(sn) == 1:
args['SubnetIds'] += [sn[0]['id']]
elif len(sn) > 1:
raise CommandExecutionError(
'Subnet Name {0} returned more than one ID.'.format(subnet))
elif subnet.startswith('subnet-'):
# Moderately safe assumption... :) Will be caught later if incorrect.
args['SubnetIds'] += [subnet]
else:
raise SaltInvocationError(
'Could not resolve Subnet Name {0} to an ID.'.format(subnet))
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
return _modify_resource(name, name_param='CacheSubnetGroupName', desc='cache subnet group',
res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete an ElastiCache subnet group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_subnet_group my-subnet-group region=us-east-1
'''
return _delete_resource(name, name_param='CacheSubnetGroupName',
desc='cache subnet group', res_type='cache_subnet_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def describe_cache_security_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_security_groups
salt myminion boto3_elasticache.describe_cache_security_groups mycachesecgrp
'''
return _describe_resource(name=name, name_param='CacheSecurityGroupName',
res_type='cache_security_group', info_node='CacheSecurityGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an ElastiCache security group exists.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup
'''
return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
profile=profile))
def create_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_security_group mycachesecgrp Description='My Cache Security Group'
'''
return _create_resource(name, name_param='CacheSecurityGroupName', desc='cache security group',
res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='CacheSecurityGroupName',
desc='cache security group', res_type='cache_security_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.authorize_cache_security_group_ingress(**args)
log.info('Authorized %s to cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def revoke_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Revoke network ingress from an ec2 security group to a cache security
group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.revoke_cache_security_group_ingress \
mycachesecgrp \
EC2SecurityGroupName=someEC2sg \
EC2SecurityGroupOwnerId=SOMEOWNERID
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'CacheSecurityGroupName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'CacheSecurityGroupName: %s'",
name, args['CacheSecurityGroupName']
)
name = args['CacheSecurityGroupName']
else:
args['CacheSubnetGroupName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.revoke_cache_security_group_ingress(**args)
log.info('Revoked %s from cache security group %s.',
args['EC2SecurityGroupName'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to update security group %s: %s', name, e)
return False
def list_tags_for_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
List tags on an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those handy, feel free to utilize this however...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_tags_for_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
r = conn.list_tags_for_resource(**args)
if r and 'Taglist' in r:
return r['TagList']
return []
except botocore.exceptions.ClientError as e:
log.error('Failed to list tags for resource %s: %s', name, e)
return []
def add_tags_to_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Add tags to an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.add_tags_to_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
Tags="[{'Key': 'TeamOwner', 'Value': 'infrastructure'}]"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.add_tags_to_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def remove_tags_from_resource(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Remove tags from an Elasticache resource.
Note that this function is essentially useless as it requires a full AWS ARN for the
resource being operated on, but there is no provided API or programmatic way to find
the ARN for a given object from its name or ID alone. It requires specific knowledge
about the account number, AWS partition, and other magic details to generate.
If you happen to have those at hand though, feel free to utilize this function...
Example:
.. code-block:: bash
salt myminion boto3_elasticache.remove_tags_from_resource \
name'=arn:aws:elasticache:us-west-2:0123456789:snapshot:mySnapshot' \
TagKeys="['TeamOwner']"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'ResourceName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'ResourceName: %s'", name, args['ResourceName']
)
name = args['ResourceName']
else:
args['ResourceName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.remove_tags_from_resource(**args)
log.info('Added tags %s to %s.', args['Tags'], name)
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to add tags to %s: %s', name, e)
return False
def copy_snapshot(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Make a copy of an existing snapshot.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.copy_snapshot name=mySnapshot \
TargetSnapshotName=copyOfMySnapshot
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if 'SourceSnapshotName' in args:
log.info(
"'name: %s' param being overridden by explicitly provided "
"'SourceSnapshotName: %s'", name, args['SourceSnapshotName']
)
name = args['SourceSnapshotName']
else:
args['SourceSnapshotName'] = name
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
try:
conn.copy_snapshot(**args)
log.info('Snapshot %s copied to %s.', name, args['TargetSnapshotName'])
return True
except botocore.exceptions.ClientError as e:
log.error('Failed to copy snapshot %s: %s', name, e)
return False
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
'''
Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
'''
return _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter_group', info_node='CacheParameterGroups',
conn=conn, region=region, key=key, keyid=keyid, profile=profile)
def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,
profile=None, **args):
'''
Returns the detailed parameter list for a particular cache parameter group.
name
The name of a specific cache parameter group to return details for.
CacheParameterGroupName
The name of a specific cache parameter group to return details for. Generally not
required, as `name` will be used if not provided.
Source
Optionally, limit the parameter types to return.
Valid values:
- user
- system
- engine-default
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user
'''
ret = {}
generic = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter', info_node='Parameters',
conn=conn, region=region, key=key, keyid=keyid, profile=profile,
**args)
specific = _describe_resource(name=name, name_param='CacheParameterGroupName',
res_type='cache_parameter',
info_node='CacheNodeTypeSpecificParameters', conn=conn,
region=region, key=key, keyid=keyid, profile=profile, **args)
ret.update({'Parameters': generic}) if generic else None
ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None
return ret
def create_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Create a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.create_cache_parameter_group \
name=myParamGroup \
CacheParameterGroupFamily=redis2.8 \
Description="My Parameter Group"
'''
return _create_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
def delete_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache parameter group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_parameter_group myParamGroup
'''
return _delete_resource(name, name_param='CacheParameterGroupName',
desc='cache parameter group', res_type='cache_parameter_group',
region=region, key=key, keyid=keyid, profile=profile, **args)
|
saltstack/salt
|
salt/modules/freebsdports.py
|
_check_portname
|
python
|
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
|
Check if portname is valid and whether or not the directory exists in the
ports tree.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L59-L73
| null |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
_options_dir
|
python
|
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
|
Retrieve the path to the dir containing OPTIONS file for a given port
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L76-L90
| null |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
_options_file_exists
|
python
|
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
|
Returns True/False based on whether or not the options file for the
specified port exists.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L93-L98
|
[
"def _options_dir(name):\n '''\n Retrieve the path to the dir containing OPTIONS file for a given port\n '''\n _check_portname(name)\n _root = '/var/db/ports'\n\n # New path: /var/db/ports/category_portname\n new_dir = os.path.join(_root, name.replace('/', '_'))\n # Old path: /var/db/ports/portname\n old_dir = os.path.join(_root, name.split('/')[-1])\n\n if os.path.isdir(old_dir):\n return old_dir\n return new_dir\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
_write_options
|
python
|
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
|
Writes a new OPTIONS file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L101-L136
| null |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
_normalize
|
python
|
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
|
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L139-L146
| null |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
install
|
python
|
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
|
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L149-L197
|
[
"def deinstall(name):\n '''\n De-install a port.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ports.deinstall security/nmap\n '''\n portpath = _check_portname(name)\n old = __salt__['pkg.list_pkgs']()\n result = __salt__['cmd.run_all'](\n ['make', 'deinstall', 'BATCH=yes'],\n cwd=portpath,\n python_shell=False\n )\n __context__.pop('pkg.list_pkgs', None)\n new = __salt__['pkg.list_pkgs']()\n return salt.utils.data.compare_dicts(old, new)\n",
"def _check_portname(name):\n '''\n Check if portname is valid and whether or not the directory exists in the\n ports tree.\n '''\n if not isinstance(name, string_types) or '/' not in name:\n raise SaltInvocationError(\n 'Invalid port name \\'{0}\\' (category required)'.format(name)\n )\n\n path = os.path.join('/usr/ports', name)\n if not os.path.isdir(path):\n raise SaltInvocationError('Path \\'{0}\\' does not exist'.format(path))\n\n return path\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
deinstall
|
python
|
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
|
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L200-L219
|
[
"def _check_portname(name):\n '''\n Check if portname is valid and whether or not the directory exists in the\n ports tree.\n '''\n if not isinstance(name, string_types) or '/' not in name:\n raise SaltInvocationError(\n 'Invalid port name \\'{0}\\' (category required)'.format(name)\n )\n\n path = os.path.join('/usr/ports', name)\n if not os.path.isdir(path):\n raise SaltInvocationError('Path \\'{0}\\' does not exist'.format(path))\n\n return path\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
rmconfig
|
python
|
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
|
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L222-L240
|
[
"def _check_portname(name):\n '''\n Check if portname is valid and whether or not the directory exists in the\n ports tree.\n '''\n if not isinstance(name, string_types) or '/' not in name:\n raise SaltInvocationError(\n 'Invalid port name \\'{0}\\' (category required)'.format(name)\n )\n\n path = os.path.join('/usr/ports', name)\n if not os.path.isdir(path):\n raise SaltInvocationError('Path \\'{0}\\' does not exist'.format(path))\n\n return path\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
showconfig
|
python
|
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
|
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L243-L319
|
[
"def _check_portname(name):\n '''\n Check if portname is valid and whether or not the directory exists in the\n ports tree.\n '''\n if not isinstance(name, string_types) or '/' not in name:\n raise SaltInvocationError(\n 'Invalid port name \\'{0}\\' (category required)'.format(name)\n )\n\n path = os.path.join('/usr/ports', name)\n if not os.path.isdir(path):\n raise SaltInvocationError('Path \\'{0}\\' does not exist'.format(path))\n\n return path\n",
"def _options_file_exists(name):\n '''\n Returns True/False based on whether or not the options file for the\n specified port exists.\n '''\n return os.path.isfile(os.path.join(_options_dir(name), 'options'))\n",
"def rmconfig(name):\n '''\n Clear the cached options for the specified port; run a ``make rmconfig``\n\n name\n The name of the port to clear\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ports.rmconfig security/nmap\n '''\n portpath = _check_portname(name)\n return __salt__['cmd.run'](\n ['make', 'rmconfig'],\n cwd=portpath,\n python_shell=False\n )\n",
"def showconfig(name, default=False, dict_return=False):\n '''\n Show the configuration options for a given port.\n\n default : False\n Show the default options for a port (not necessarily the same as the\n current configuration)\n\n dict_return : False\n Instead of returning the output of ``make showconfig``, return the data\n in an dictionary\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ports.showconfig security/nmap\n salt '*' ports.showconfig security/nmap default=True\n '''\n portpath = _check_portname(name)\n\n if default and _options_file_exists(name):\n saved_config = showconfig(name, default=False, dict_return=True)\n rmconfig(name)\n if _options_file_exists(name):\n raise CommandExecutionError('Unable to get default configuration')\n default_config = showconfig(name, default=False,\n dict_return=dict_return)\n _write_options(name, saved_config)\n return default_config\n\n try:\n result = __salt__['cmd.run_all'](\n ['make', 'showconfig'],\n cwd=portpath,\n python_shell=False\n )\n output = result['stdout'].splitlines()\n if result['retcode'] != 0:\n error = result['stderr']\n else:\n error = ''\n except TypeError:\n error = result\n\n if error:\n msg = ('Error running \\'make showconfig\\' for {0}: {1}'\n .format(name, error))\n log.error(msg)\n raise SaltInvocationError(msg)\n\n if not dict_return:\n return '\\n'.join(output)\n\n if (not output) or ('configuration options' not in output[0]):\n return {}\n\n try:\n pkg = output[0].split()[-1].rstrip(':')\n except (IndexError, AttributeError, TypeError) as exc:\n log.error('Unable to get pkg-version string: %s', exc)\n return {}\n\n ret = {pkg: {}}\n output = output[1:]\n for line in output:\n try:\n opt, val, desc = re.match(\n r'\\s+([^=]+)=(off|on): (.+)', line\n ).groups()\n except AttributeError:\n continue\n ret[pkg][opt] = val\n\n if not ret[pkg]:\n return {}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
config
|
python
|
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
|
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L322-L389
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _check_portname(name):\n '''\n Check if portname is valid and whether or not the directory exists in the\n ports tree.\n '''\n if not isinstance(name, string_types) or '/' not in name:\n raise SaltInvocationError(\n 'Invalid port name \\'{0}\\' (category required)'.format(name)\n )\n\n path = os.path.join('/usr/ports', name)\n if not os.path.isdir(path):\n raise SaltInvocationError('Path \\'{0}\\' does not exist'.format(path))\n\n return path\n",
"def _write_options(name, configuration):\n '''\n Writes a new OPTIONS file\n '''\n _check_portname(name)\n\n pkg = next(iter(configuration))\n conf_ptr = configuration[pkg]\n\n dirname = _options_dir(name)\n if not os.path.isdir(dirname):\n try:\n os.makedirs(dirname)\n except OSError as exc:\n raise CommandExecutionError(\n 'Unable to make {0}: {1}'.format(dirname, exc)\n )\n\n with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:\n sorted_options = list(conf_ptr)\n sorted_options.sort()\n fp_.write(salt.utils.stringutils.to_str(\n '# This file was auto-generated by Salt (http://saltstack.com)\\n'\n '# Options for {0}\\n'\n '_OPTIONS_READ={0}\\n'\n '_FILE_COMPLETE_OPTIONS_LIST={1}\\n'\n .format(pkg, ' '.join(sorted_options))\n ))\n opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\\n'\n for opt in sorted_options:\n fp_.write(salt.utils.stringutils.to_str(\n opt_tmpl.format(\n '' if conf_ptr[opt] == 'on' else 'UN',\n opt\n )\n ))\n",
"def rmconfig(name):\n '''\n Clear the cached options for the specified port; run a ``make rmconfig``\n\n name\n The name of the port to clear\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ports.rmconfig security/nmap\n '''\n portpath = _check_portname(name)\n return __salt__['cmd.run'](\n ['make', 'rmconfig'],\n cwd=portpath,\n python_shell=False\n )\n",
"def showconfig(name, default=False, dict_return=False):\n '''\n Show the configuration options for a given port.\n\n default : False\n Show the default options for a port (not necessarily the same as the\n current configuration)\n\n dict_return : False\n Instead of returning the output of ``make showconfig``, return the data\n in an dictionary\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ports.showconfig security/nmap\n salt '*' ports.showconfig security/nmap default=True\n '''\n portpath = _check_portname(name)\n\n if default and _options_file_exists(name):\n saved_config = showconfig(name, default=False, dict_return=True)\n rmconfig(name)\n if _options_file_exists(name):\n raise CommandExecutionError('Unable to get default configuration')\n default_config = showconfig(name, default=False,\n dict_return=dict_return)\n _write_options(name, saved_config)\n return default_config\n\n try:\n result = __salt__['cmd.run_all'](\n ['make', 'showconfig'],\n cwd=portpath,\n python_shell=False\n )\n output = result['stdout'].splitlines()\n if result['retcode'] != 0:\n error = result['stderr']\n else:\n error = ''\n except TypeError:\n error = result\n\n if error:\n msg = ('Error running \\'make showconfig\\' for {0}: {1}'\n .format(name, error))\n log.error(msg)\n raise SaltInvocationError(msg)\n\n if not dict_return:\n return '\\n'.join(output)\n\n if (not output) or ('configuration options' not in output[0]):\n return {}\n\n try:\n pkg = output[0].split()[-1].rstrip(':')\n except (IndexError, AttributeError, TypeError) as exc:\n log.error('Unable to get pkg-version string: %s', exc)\n return {}\n\n ret = {pkg: {}}\n output = output[1:]\n for line in output:\n try:\n opt, val, desc = re.match(\n r'\\s+([^=]+)=(off|on): (.+)', line\n ).groups()\n except AttributeError:\n continue\n ret[pkg][opt] = val\n\n if not ret[pkg]:\n return {}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
update
|
python
|
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
|
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L392-L453
|
[
"def _portsnap():\n '''\n Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'\n '''\n ret = ['portsnap']\n if float(__grains__['osrelease']) >= 10:\n ret.append('--interactive')\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
list_all
|
python
|
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
|
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L456-L477
|
[
"def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
saltstack/salt
|
salt/modules/freebsdports.py
|
search
|
python
|
def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
'''
name = six.text_type(name)
all_ports = list_all()
if '/' in name:
if name.count('/') > 1:
raise SaltInvocationError(
'Invalid search string \'{0}\'. Port names cannot have more '
'than one slash'
)
else:
return fnmatch.filter(all_ports, name)
else:
ret = []
for port in all_ports:
if fnmatch.fnmatch(port.rsplit('/')[-1], name):
ret.append(port)
return ret
|
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L480-L512
|
[
"def list_all():\n '''\n Lists all ports available.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ports.list_all\n\n .. warning::\n\n Takes a while to run, and returns a **LOT** of output\n '''\n if 'ports.list_all' not in __context__:\n __context__['ports.list_all'] = []\n for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):\n stripped = path[len('/usr/ports'):]\n if stripped.count('/') != 2 or stripped.endswith('/CVS'):\n continue\n __context__['ports.list_all'].append(stripped[1:])\n return __context__['ports.list_all']\n"
] |
# -*- coding: utf-8 -*-
'''
Install software from the FreeBSD ``ports(7)`` system
.. versionadded:: 2014.1.0
This module allows you to install ports using ``BATCH=yes`` to bypass
configuration prompts. It is recommended to use the :mod:`ports state
<salt.states.freebsdports>` to install ports, but it is also possible to use
this module exclusively from the command line.
.. code-block:: bash
salt minion-id ports.config security/nmap IPV6=off
salt minion-id ports.install security/nmap
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import fnmatch
import os
import re
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.path
from salt.ext.six import string_types
from salt.exceptions import SaltInvocationError, CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'ports'
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsdports execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _portsnap():
'''
Return 'portsnap --interactive' for FreeBSD 10, otherwise 'portsnap'
'''
ret = ['portsnap']
if float(__grains__['osrelease']) >= 10:
ret.append('--interactive')
return ret
def _check_portname(name):
'''
Check if portname is valid and whether or not the directory exists in the
ports tree.
'''
if not isinstance(name, string_types) or '/' not in name:
raise SaltInvocationError(
'Invalid port name \'{0}\' (category required)'.format(name)
)
path = os.path.join('/usr/ports', name)
if not os.path.isdir(path):
raise SaltInvocationError('Path \'{0}\' does not exist'.format(path))
return path
def _options_dir(name):
'''
Retrieve the path to the dir containing OPTIONS file for a given port
'''
_check_portname(name)
_root = '/var/db/ports'
# New path: /var/db/ports/category_portname
new_dir = os.path.join(_root, name.replace('/', '_'))
# Old path: /var/db/ports/portname
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir
def _options_file_exists(name):
'''
Returns True/False based on whether or not the options file for the
specified port exists.
'''
return os.path.isfile(os.path.join(_options_dir(name), 'options'))
def _write_options(name, configuration):
'''
Writes a new OPTIONS file
'''
_check_portname(name)
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
dirname = _options_dir(name)
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except OSError as exc:
raise CommandExecutionError(
'Unable to make {0}: {1}'.format(dirname, exc)
)
with salt.utils.files.fopen(os.path.join(dirname, 'options'), 'w') as fp_:
sorted_options = list(conf_ptr)
sorted_options.sort()
fp_.write(salt.utils.stringutils.to_str(
'# This file was auto-generated by Salt (http://saltstack.com)\n'
'# Options for {0}\n'
'_OPTIONS_READ={0}\n'
'_FILE_COMPLETE_OPTIONS_LIST={1}\n'
.format(pkg, ' '.join(sorted_options))
))
opt_tmpl = 'OPTIONS_FILE_{0}SET+={1}\n'
for opt in sorted_options:
fp_.write(salt.utils.stringutils.to_str(
opt_tmpl.format(
'' if conf_ptr[opt] == 'on' else 'UN',
opt
)
))
def _normalize(val):
'''
Fix Salt's yaml-ification of on/off, and otherwise normalize the on/off
values to be used in writing the options file
'''
if isinstance(val, bool):
return 'on' if val else 'off'
return six.text_type(val).lower()
def install(name, clean=True):
'''
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivalent to running ``make
install clean BATCH=yes``.
.. note::
It may be helpful to run this function using the ``-t`` option to set a
higher timeout, since compiling a port may cause the Salt command to
exceed the default timeout.
CLI Example:
.. code-block:: bash
salt -t 1200 '*' ports.install security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
if old.get(name.rsplit('/')[-1]):
deinstall(name)
cmd = ['make', 'install']
if clean:
cmd.append('clean')
cmd.append('BATCH=yes')
result = __salt__['cmd.run_all'](
cmd,
cwd=portpath,
reset_system_locale=False,
python_shell=False
)
if result['retcode'] != 0:
__context__['ports.install_error'] = result['stderr']
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
ret = salt.utils.data.compare_dicts(old, new)
if not ret and result['retcode'] == 0:
# No change in package list, but the make install was successful.
# Assume that the installation was a recompile with new options, and
# set return dict so that changes are detected by the ports.installed
# state.
ret = {name: {'old': old.get(name, ''),
'new': new.get(name, '')}}
return ret
def deinstall(name):
'''
De-install a port.
CLI Example:
.. code-block:: bash
salt '*' ports.deinstall security/nmap
'''
portpath = _check_portname(name)
old = __salt__['pkg.list_pkgs']()
result = __salt__['cmd.run_all'](
['make', 'deinstall', 'BATCH=yes'],
cwd=portpath,
python_shell=False
)
__context__.pop('pkg.list_pkgs', None)
new = __salt__['pkg.list_pkgs']()
return salt.utils.data.compare_dicts(old, new)
def rmconfig(name):
'''
Clear the cached options for the specified port; run a ``make rmconfig``
name
The name of the port to clear
CLI Example:
.. code-block:: bash
salt '*' ports.rmconfig security/nmap
'''
portpath = _check_portname(name)
return __salt__['cmd.run'](
['make', 'rmconfig'],
cwd=portpath,
python_shell=False
)
def showconfig(name, default=False, dict_return=False):
'''
Show the configuration options for a given port.
default : False
Show the default options for a port (not necessarily the same as the
current configuration)
dict_return : False
Instead of returning the output of ``make showconfig``, return the data
in an dictionary
CLI Example:
.. code-block:: bash
salt '*' ports.showconfig security/nmap
salt '*' ports.showconfig security/nmap default=True
'''
portpath = _check_portname(name)
if default and _options_file_exists(name):
saved_config = showconfig(name, default=False, dict_return=True)
rmconfig(name)
if _options_file_exists(name):
raise CommandExecutionError('Unable to get default configuration')
default_config = showconfig(name, default=False,
dict_return=dict_return)
_write_options(name, saved_config)
return default_config
try:
result = __salt__['cmd.run_all'](
['make', 'showconfig'],
cwd=portpath,
python_shell=False
)
output = result['stdout'].splitlines()
if result['retcode'] != 0:
error = result['stderr']
else:
error = ''
except TypeError:
error = result
if error:
msg = ('Error running \'make showconfig\' for {0}: {1}'
.format(name, error))
log.error(msg)
raise SaltInvocationError(msg)
if not dict_return:
return '\n'.join(output)
if (not output) or ('configuration options' not in output[0]):
return {}
try:
pkg = output[0].split()[-1].rstrip(':')
except (IndexError, AttributeError, TypeError) as exc:
log.error('Unable to get pkg-version string: %s', exc)
return {}
ret = {pkg: {}}
output = output[1:]
for line in output:
try:
opt, val, desc = re.match(
r'\s+([^=]+)=(off|on): (.+)', line
).groups()
except AttributeError:
continue
ret[pkg][opt] = val
if not ret[pkg]:
return {}
return ret
def config(name, reset=False, **kwargs):
'''
Modify configuration options for a given port. Multiple options can be
specified. To see the available options for a port, use
:mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`.
name
The port name, in ``category/name`` format
reset : False
If ``True``, runs a ``make rmconfig`` for the port, clearing its
configuration before setting the desired options
CLI Examples:
.. code-block:: bash
salt '*' ports.config security/nmap IPV6=off
'''
portpath = _check_portname(name)
if reset:
rmconfig(name)
configuration = showconfig(name, dict_return=True)
if not configuration:
raise CommandExecutionError(
'Unable to get port configuration for \'{0}\''.format(name)
)
# Get top-level key for later reference
pkg = next(iter(configuration))
conf_ptr = configuration[pkg]
opts = dict(
(six.text_type(x), _normalize(kwargs[x]))
for x in kwargs
if not x.startswith('_')
)
bad_opts = [x for x in opts if x not in conf_ptr]
if bad_opts:
raise SaltInvocationError(
'The following opts are not valid for port {0}: {1}'
.format(name, ', '.join(bad_opts))
)
bad_vals = [
'{0}={1}'.format(x, y) for x, y in six.iteritems(opts)
if y not in ('on', 'off')
]
if bad_vals:
raise SaltInvocationError(
'The following key/value pairs are invalid: {0}'
.format(', '.join(bad_vals))
)
conf_ptr.update(opts)
_write_options(name, configuration)
new_config = showconfig(name, dict_return=True)
try:
new_config = new_config[next(iter(new_config))]
except (StopIteration, TypeError):
return False
return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
def update(extract=False):
'''
Update the ports tree
extract : False
If ``True``, runs a ``portsnap extract`` after fetching, should be used
for first-time installation of the ports tree.
CLI Example:
.. code-block:: bash
salt '*' ports.update
'''
result = __salt__['cmd.run_all'](
_portsnap() + ['fetch'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to fetch ports snapshot: {0}'.format(result['stderr'])
)
ret = []
try:
patch_count = re.search(
r'Fetching (\d+) patches', result['stdout']
).group(1)
except AttributeError:
patch_count = 0
try:
new_port_count = re.search(
r'Fetching (\d+) new ports or files', result['stdout']
).group(1)
except AttributeError:
new_port_count = 0
ret.append('Applied {0} new patches'.format(patch_count))
ret.append('Fetched {0} new ports or files'.format(new_port_count))
if extract:
result = __salt__['cmd.run_all'](
_portsnap() + ['extract'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to extract ports snapshot {0}'.format(result['stderr'])
)
result = __salt__['cmd.run_all'](
_portsnap() + ['update'],
python_shell=False
)
if not result['retcode'] == 0:
raise CommandExecutionError(
'Unable to apply ports snapshot: {0}'.format(result['stderr'])
)
__context__.pop('ports.list_all', None)
return '\n'.join(ret)
def list_all():
'''
Lists all ports available.
CLI Example:
.. code-block:: bash
salt '*' ports.list_all
.. warning::
Takes a while to run, and returns a **LOT** of output
'''
if 'ports.list_all' not in __context__:
__context__['ports.list_all'] = []
for path, dirs, files in salt.utils.path.os_walk('/usr/ports'):
stripped = path[len('/usr/ports'):]
if stripped.count('/') != 2 or stripped.endswith('/CVS'):
continue
__context__['ports.list_all'].append(stripped[1:])
return __context__['ports.list_all']
|
saltstack/salt
|
salt/modules/textfsm_mod.py
|
_clitable_to_dict
|
python
|
def _clitable_to_dict(objects, fsm_handler):
'''
Converts TextFSM cli_table object to list of dictionaries.
'''
objs = []
log.debug('Cli Table:')
log.debug(objects)
log.debug('FSM handler:')
log.debug(fsm_handler)
for row in objects:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[fsm_handler.header[index].lower()] = element
objs.append(temp_dict)
log.debug('Extraction result:')
log.debug(objs)
return objs
|
Converts TextFSM cli_table object to list of dictionaries.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/textfsm_mod.py#L59-L75
| null |
# -*- coding: utf-8 -*-
'''
TextFSM
=======
.. versionadded:: 2018.3.0
Execution module that processes plain text and extracts data
using TextFSM templates. The output is presented in JSON serializable
data, and can be easily re-used in other modules, or directly
inside the renderer (Jinja, Mako, Genshi, etc.).
:depends: - textfsm Python library
.. note::
For Python 2/3 compatibility, it is more recommended to
install the ``jtextfsm`` library: ``pip install jtextfsm``.
'''
from __future__ import absolute_import
# Import python libs
import os
import logging
# Import third party modules
try:
import textfsm
HAS_TEXTFSM = True
except ImportError:
HAS_TEXTFSM = False
try:
import clitable
HAS_CLITABLE = True
except ImportError:
HAS_CLITABLE = False
try:
from salt.utils.files import fopen
except ImportError:
from salt.utils import fopen
log = logging.getLogger(__name__)
__virtualname__ = 'textfsm'
__proxyenabled__ = ['*']
def __virtual__():
'''
Only load this execution module if TextFSM is installed.
'''
if HAS_TEXTFSM:
return __virtualname__
return (False, 'The textfsm execution module failed to load: requires the textfsm library.')
def extract(template_path, raw_text=None, raw_text_file=None, saltenv='base'):
r'''
Extracts the data entities from the unstructured
raw text sent as input and returns the data
mapping, processing using the TextFSM template.
template_path
The path to the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
raw_text: ``None``
The unstructured text to be parsed.
raw_text_file: ``None``
Text file to read, having the raw text to be parsed using the TextFSM template.
Supports the same URL schemes as the ``template_path`` argument.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``template_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' textfsm.extract salt://textfsm/juniper_version_template raw_text_file=s3://junos_ver.txt
salt '*' textfsm.extract http://some-server/textfsm/juniper_version_template raw_text='Hostname: router.abc ... snip ...'
Jinja template example:
.. code-block:: jinja
{%- set raw_text = 'Hostname: router.abc ... snip ...' -%}
{%- set textfsm_extract = salt.textfsm.extract('https://some-server/textfsm/juniper_version_template', raw_text) -%}
Raw text example:
.. code-block:: text
Hostname: router.abc
Model: mx960
JUNOS Base OS boot [9.1S3.5]
JUNOS Base OS Software Suite [9.1S3.5]
JUNOS Kernel Software Suite [9.1S3.5]
JUNOS Crypto Software Suite [9.1S3.5]
JUNOS Packet Forwarding Engine Support (M/T Common) [9.1S3.5]
JUNOS Packet Forwarding Engine Support (MX Common) [9.1S3.5]
JUNOS Online Documentation [9.1S3.5]
JUNOS Routing Software Suite [9.1S3.5]
TextFSM Example:
.. code-block:: text
Value Chassis (\S+)
Value Required Model (\S+)
Value Boot (.*)
Value Base (.*)
Value Kernel (.*)
Value Crypto (.*)
Value Documentation (.*)
Value Routing (.*)
Start
# Support multiple chassis systems.
^\S+:$$ -> Continue.Record
^${Chassis}:$$
^Model: ${Model}
^JUNOS Base OS boot \[${Boot}\]
^JUNOS Software Release \[${Base}\]
^JUNOS Base OS Software Suite \[${Base}\]
^JUNOS Kernel Software Suite \[${Kernel}\]
^JUNOS Crypto Software Suite \[${Crypto}\]
^JUNOS Online Documentation \[${Documentation}\]
^JUNOS Routing Software Suite \[${Routing}\]
Output example:
.. code-block:: json
{
"comment": "",
"result": true,
"out": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
'''
ret = {
'result': False,
'comment': '',
'out': None
}
log.debug('Using the saltenv: %s', saltenv)
log.debug('Caching %s using the Salt fileserver', template_path)
tpl_cached_path = __salt__['cp.cache_file'](template_path, saltenv=saltenv)
if tpl_cached_path is False:
ret['comment'] = 'Unable to read the TextFSM template from {}'.format(template_path)
log.error(ret['comment'])
return ret
try:
log.debug('Reading TextFSM template from cache path: %s', tpl_cached_path)
# Disabling pylint W8470 to nto complain about fopen.
# Unfortunately textFSM needs the file handle rather than the content...
# pylint: disable=W8470
tpl_file_handle = fopen(tpl_cached_path, 'r')
# pylint: disable=W8470
log.debug(tpl_file_handle.read())
tpl_file_handle.seek(0) # move the object position back at the top of the file
fsm_handler = textfsm.TextFSM(tpl_file_handle)
except textfsm.TextFSMTemplateError as tfte:
log.error('Unable to parse the TextFSM template', exc_info=True)
ret['comment'] = 'Unable to parse the TextFSM template from {}: {}. Please check the logs.'.format(
template_path, tfte)
return ret
if not raw_text and raw_text_file:
log.debug('Trying to read the raw input from %s', raw_text_file)
raw_text = __salt__['cp.get_file_str'](raw_text_file, saltenv=saltenv)
if raw_text is False:
ret['comment'] = 'Unable to read from {}. Please specify a valid input file or text.'.format(raw_text_file)
log.error(ret['comment'])
return ret
if not raw_text:
ret['comment'] = 'Please specify a valid input file or text.'
log.error(ret['comment'])
return ret
log.debug('Processing the raw text:')
log.debug(raw_text)
objects = fsm_handler.ParseText(raw_text)
ret['out'] = _clitable_to_dict(objects, fsm_handler)
ret['result'] = True
return ret
def index(command,
platform=None,
platform_grain_name=None,
platform_column_name=None,
output=None,
output_file=None,
textfsm_path=None,
index_file=None,
saltenv='base',
include_empty=False,
include_pat=None,
exclude_pat=None):
'''
Dynamically identify the template required to extract the
information from the unstructured raw text.
The output has the same structure as the ``extract`` execution
function, the difference being that ``index`` is capable
to identify what template to use, based on the platform
details and the ``command``.
command
The command executed on the device, to get the output.
platform
The platform name, as defined in the TextFSM index file.
.. note::
For ease of use, it is recommended to define the TextFSM
indexfile with values that can be matches using the grains.
platform_grain_name
The name of the grain used to identify the platform name
in the TextFSM index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
.. note::
This option is ignored when ``platform`` is specified.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
output
The raw output from the device, to be parsed
and extract the structured data.
output_file
The path to a file that contains the raw output from the device,
used to extract the structured data.
This option supports the usual Salt-specific schemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``, ``s3://``, ``swift://``.
textfsm_path
The path where the TextFSM templates can be found. This can be either
absolute path on the server, either specified using the following URL
schemes: ``file://``, ``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
include_empty: ``False``
Include empty files under the ``textfsm_path``.
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' platform=Juniper output_file=salt://textfsm/juniper_version_example textfsm_path=salt://textfsm/
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=ftp://textfsm/ platform_column_name=Vendor
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=https://some-server/textfsm/ platform_column_name=Vendor platform_grain_name=vendor
TextFSM index file example:
``salt://textfsm/index``
.. code-block:: text
Template, Hostname, Vendor, Command
juniper_version_template, .*, Juniper, sh[[ow]] ve[[rsion]]
The usage can be simplified,
by defining (some of) the following options: ``textfsm_platform_grain``,
``textfsm_path``, ``textfsm_platform_column_name``, or ``textfsm_index_file``,
in the (proxy) minion configuration file or pillar.
Configuration example:
.. code-block:: yaml
textfsm_platform_grain: vendor
textfsm_path: salt://textfsm/
textfsm_platform_column_name: Vendor
And the CLI usage becomes as simple as:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example
Usgae inside a Jinja template:
.. code-block:: jinja
{%- set command = 'sh ver' -%}
{%- set output = salt.net.cli(command) -%}
{%- set textfsm_extract = salt.textfsm.index(command, output=output) -%}
'''
ret = {
'out': None,
'result': False,
'comment': ''
}
if not HAS_CLITABLE:
ret['comment'] = 'TextFSM doesnt seem that has clitable embedded.'
log.error(ret['comment'])
return ret
if not platform:
platform_grain_name = __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', platform_grain_name)
if platform_grain_name:
log.debug('Using the %s grain to identify the platform name', platform_grain_name)
platform = __grains__.get(platform_grain_name)
if not platform:
ret['comment'] = 'Unable to identify the platform name using the {} grain.'.format(platform_grain_name)
return ret
log.info('Using platform: %s', platform)
else:
ret['comment'] = 'No platform specified, no platform grain identifier configured.'
log.error(ret['comment'])
return ret
if not textfsm_path:
log.debug('No TextFSM templates path specified, trying to look into the opts and pillar')
textfsm_path = __opts__.get('textfsm_path') or __pillar__.get('textfsm_path')
if not textfsm_path:
ret['comment'] = 'No TextFSM templates path specified. Please configure in opts/pillar/function args.'
log.error(ret['comment'])
return ret
log.debug('Using the saltenv: %s', saltenv)
log.debug('Caching %s using the Salt fileserver', textfsm_path)
textfsm_cachedir_ret = __salt__['cp.cache_dir'](textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Cache fun return:')
log.debug(textfsm_cachedir_ret)
if not textfsm_cachedir_ret:
ret['comment'] = 'Unable to fetch from {}. Is the TextFSM path correctly specified?'.format(textfsm_path)
log.error(ret['comment'])
return ret
textfsm_cachedir = os.path.dirname(textfsm_cachedir_ret[0]) # first item
index_file = __opts__.get('textfsm_index_file') or __pillar__.get('textfsm_index_file', 'index')
index_file_path = os.path.join(textfsm_cachedir, index_file)
log.debug('Using the cached index file: %s', index_file_path)
log.debug('TextFSM templates cached under: %s', textfsm_cachedir)
textfsm_obj = clitable.CliTable(index_file_path, textfsm_cachedir)
attrs = {
'Command': command
}
platform_column_name = __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.info('Using the TextFSM platform idenfiticator: %s', platform_column_name)
attrs[platform_column_name] = platform
log.debug('Processing the TextFSM index file using the attributes: %s', attrs)
if not output and output_file:
log.debug('Processing the output from %s', output_file)
output = __salt__['cp.get_file_str'](output_file, saltenv=saltenv)
if output is False:
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(output_file)
log.error(ret['comment'])
return ret
if not output:
ret['comment'] = 'Please specify a valid output text or file'
log.error(ret['comment'])
return ret
log.debug('Processing the raw text:')
log.debug(output)
try:
# Parse output through template
textfsm_obj.ParseCmd(output, attrs)
ret['out'] = _clitable_to_dict(textfsm_obj, textfsm_obj)
ret['result'] = True
except clitable.CliTableError as cterr:
log.error('Unable to proces the CliTable', exc_info=True)
ret['comment'] = 'Unable to process the output: {}'.format(cterr)
return ret
|
saltstack/salt
|
salt/modules/textfsm_mod.py
|
extract
|
python
|
def extract(template_path, raw_text=None, raw_text_file=None, saltenv='base'):
r'''
Extracts the data entities from the unstructured
raw text sent as input and returns the data
mapping, processing using the TextFSM template.
template_path
The path to the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
raw_text: ``None``
The unstructured text to be parsed.
raw_text_file: ``None``
Text file to read, having the raw text to be parsed using the TextFSM template.
Supports the same URL schemes as the ``template_path`` argument.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``template_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' textfsm.extract salt://textfsm/juniper_version_template raw_text_file=s3://junos_ver.txt
salt '*' textfsm.extract http://some-server/textfsm/juniper_version_template raw_text='Hostname: router.abc ... snip ...'
Jinja template example:
.. code-block:: jinja
{%- set raw_text = 'Hostname: router.abc ... snip ...' -%}
{%- set textfsm_extract = salt.textfsm.extract('https://some-server/textfsm/juniper_version_template', raw_text) -%}
Raw text example:
.. code-block:: text
Hostname: router.abc
Model: mx960
JUNOS Base OS boot [9.1S3.5]
JUNOS Base OS Software Suite [9.1S3.5]
JUNOS Kernel Software Suite [9.1S3.5]
JUNOS Crypto Software Suite [9.1S3.5]
JUNOS Packet Forwarding Engine Support (M/T Common) [9.1S3.5]
JUNOS Packet Forwarding Engine Support (MX Common) [9.1S3.5]
JUNOS Online Documentation [9.1S3.5]
JUNOS Routing Software Suite [9.1S3.5]
TextFSM Example:
.. code-block:: text
Value Chassis (\S+)
Value Required Model (\S+)
Value Boot (.*)
Value Base (.*)
Value Kernel (.*)
Value Crypto (.*)
Value Documentation (.*)
Value Routing (.*)
Start
# Support multiple chassis systems.
^\S+:$$ -> Continue.Record
^${Chassis}:$$
^Model: ${Model}
^JUNOS Base OS boot \[${Boot}\]
^JUNOS Software Release \[${Base}\]
^JUNOS Base OS Software Suite \[${Base}\]
^JUNOS Kernel Software Suite \[${Kernel}\]
^JUNOS Crypto Software Suite \[${Crypto}\]
^JUNOS Online Documentation \[${Documentation}\]
^JUNOS Routing Software Suite \[${Routing}\]
Output example:
.. code-block:: json
{
"comment": "",
"result": true,
"out": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
'''
ret = {
'result': False,
'comment': '',
'out': None
}
log.debug('Using the saltenv: %s', saltenv)
log.debug('Caching %s using the Salt fileserver', template_path)
tpl_cached_path = __salt__['cp.cache_file'](template_path, saltenv=saltenv)
if tpl_cached_path is False:
ret['comment'] = 'Unable to read the TextFSM template from {}'.format(template_path)
log.error(ret['comment'])
return ret
try:
log.debug('Reading TextFSM template from cache path: %s', tpl_cached_path)
# Disabling pylint W8470 to nto complain about fopen.
# Unfortunately textFSM needs the file handle rather than the content...
# pylint: disable=W8470
tpl_file_handle = fopen(tpl_cached_path, 'r')
# pylint: disable=W8470
log.debug(tpl_file_handle.read())
tpl_file_handle.seek(0) # move the object position back at the top of the file
fsm_handler = textfsm.TextFSM(tpl_file_handle)
except textfsm.TextFSMTemplateError as tfte:
log.error('Unable to parse the TextFSM template', exc_info=True)
ret['comment'] = 'Unable to parse the TextFSM template from {}: {}. Please check the logs.'.format(
template_path, tfte)
return ret
if not raw_text and raw_text_file:
log.debug('Trying to read the raw input from %s', raw_text_file)
raw_text = __salt__['cp.get_file_str'](raw_text_file, saltenv=saltenv)
if raw_text is False:
ret['comment'] = 'Unable to read from {}. Please specify a valid input file or text.'.format(raw_text_file)
log.error(ret['comment'])
return ret
if not raw_text:
ret['comment'] = 'Please specify a valid input file or text.'
log.error(ret['comment'])
return ret
log.debug('Processing the raw text:')
log.debug(raw_text)
objects = fsm_handler.ParseText(raw_text)
ret['out'] = _clitable_to_dict(objects, fsm_handler)
ret['result'] = True
return ret
|
r'''
Extracts the data entities from the unstructured
raw text sent as input and returns the data
mapping, processing using the TextFSM template.
template_path
The path to the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
raw_text: ``None``
The unstructured text to be parsed.
raw_text_file: ``None``
Text file to read, having the raw text to be parsed using the TextFSM template.
Supports the same URL schemes as the ``template_path`` argument.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``template_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' textfsm.extract salt://textfsm/juniper_version_template raw_text_file=s3://junos_ver.txt
salt '*' textfsm.extract http://some-server/textfsm/juniper_version_template raw_text='Hostname: router.abc ... snip ...'
Jinja template example:
.. code-block:: jinja
{%- set raw_text = 'Hostname: router.abc ... snip ...' -%}
{%- set textfsm_extract = salt.textfsm.extract('https://some-server/textfsm/juniper_version_template', raw_text) -%}
Raw text example:
.. code-block:: text
Hostname: router.abc
Model: mx960
JUNOS Base OS boot [9.1S3.5]
JUNOS Base OS Software Suite [9.1S3.5]
JUNOS Kernel Software Suite [9.1S3.5]
JUNOS Crypto Software Suite [9.1S3.5]
JUNOS Packet Forwarding Engine Support (M/T Common) [9.1S3.5]
JUNOS Packet Forwarding Engine Support (MX Common) [9.1S3.5]
JUNOS Online Documentation [9.1S3.5]
JUNOS Routing Software Suite [9.1S3.5]
TextFSM Example:
.. code-block:: text
Value Chassis (\S+)
Value Required Model (\S+)
Value Boot (.*)
Value Base (.*)
Value Kernel (.*)
Value Crypto (.*)
Value Documentation (.*)
Value Routing (.*)
Start
# Support multiple chassis systems.
^\S+:$$ -> Continue.Record
^${Chassis}:$$
^Model: ${Model}
^JUNOS Base OS boot \[${Boot}\]
^JUNOS Software Release \[${Base}\]
^JUNOS Base OS Software Suite \[${Base}\]
^JUNOS Kernel Software Suite \[${Kernel}\]
^JUNOS Crypto Software Suite \[${Crypto}\]
^JUNOS Online Documentation \[${Documentation}\]
^JUNOS Routing Software Suite \[${Routing}\]
Output example:
.. code-block:: json
{
"comment": "",
"result": true,
"out": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/textfsm_mod.py#L78-L225
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _clitable_to_dict(objects, fsm_handler):\n '''\n Converts TextFSM cli_table object to list of dictionaries.\n '''\n objs = []\n log.debug('Cli Table:')\n log.debug(objects)\n log.debug('FSM handler:')\n log.debug(fsm_handler)\n for row in objects:\n temp_dict = {}\n for index, element in enumerate(row):\n temp_dict[fsm_handler.header[index].lower()] = element\n objs.append(temp_dict)\n log.debug('Extraction result:')\n log.debug(objs)\n return objs\n"
] |
# -*- coding: utf-8 -*-
'''
TextFSM
=======
.. versionadded:: 2018.3.0
Execution module that processes plain text and extracts data
using TextFSM templates. The output is presented in JSON serializable
data, and can be easily re-used in other modules, or directly
inside the renderer (Jinja, Mako, Genshi, etc.).
:depends: - textfsm Python library
.. note::
For Python 2/3 compatibility, it is more recommended to
install the ``jtextfsm`` library: ``pip install jtextfsm``.
'''
from __future__ import absolute_import
# Import python libs
import os
import logging
# Import third party modules
try:
import textfsm
HAS_TEXTFSM = True
except ImportError:
HAS_TEXTFSM = False
try:
import clitable
HAS_CLITABLE = True
except ImportError:
HAS_CLITABLE = False
try:
from salt.utils.files import fopen
except ImportError:
from salt.utils import fopen
log = logging.getLogger(__name__)
__virtualname__ = 'textfsm'
__proxyenabled__ = ['*']
def __virtual__():
'''
Only load this execution module if TextFSM is installed.
'''
if HAS_TEXTFSM:
return __virtualname__
return (False, 'The textfsm execution module failed to load: requires the textfsm library.')
def _clitable_to_dict(objects, fsm_handler):
'''
Converts TextFSM cli_table object to list of dictionaries.
'''
objs = []
log.debug('Cli Table:')
log.debug(objects)
log.debug('FSM handler:')
log.debug(fsm_handler)
for row in objects:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[fsm_handler.header[index].lower()] = element
objs.append(temp_dict)
log.debug('Extraction result:')
log.debug(objs)
return objs
def index(command,
platform=None,
platform_grain_name=None,
platform_column_name=None,
output=None,
output_file=None,
textfsm_path=None,
index_file=None,
saltenv='base',
include_empty=False,
include_pat=None,
exclude_pat=None):
'''
Dynamically identify the template required to extract the
information from the unstructured raw text.
The output has the same structure as the ``extract`` execution
function, the difference being that ``index`` is capable
to identify what template to use, based on the platform
details and the ``command``.
command
The command executed on the device, to get the output.
platform
The platform name, as defined in the TextFSM index file.
.. note::
For ease of use, it is recommended to define the TextFSM
indexfile with values that can be matches using the grains.
platform_grain_name
The name of the grain used to identify the platform name
in the TextFSM index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
.. note::
This option is ignored when ``platform`` is specified.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
output
The raw output from the device, to be parsed
and extract the structured data.
output_file
The path to a file that contains the raw output from the device,
used to extract the structured data.
This option supports the usual Salt-specific schemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``, ``s3://``, ``swift://``.
textfsm_path
The path where the TextFSM templates can be found. This can be either
absolute path on the server, either specified using the following URL
schemes: ``file://``, ``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
include_empty: ``False``
Include empty files under the ``textfsm_path``.
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' platform=Juniper output_file=salt://textfsm/juniper_version_example textfsm_path=salt://textfsm/
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=ftp://textfsm/ platform_column_name=Vendor
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=https://some-server/textfsm/ platform_column_name=Vendor platform_grain_name=vendor
TextFSM index file example:
``salt://textfsm/index``
.. code-block:: text
Template, Hostname, Vendor, Command
juniper_version_template, .*, Juniper, sh[[ow]] ve[[rsion]]
The usage can be simplified,
by defining (some of) the following options: ``textfsm_platform_grain``,
``textfsm_path``, ``textfsm_platform_column_name``, or ``textfsm_index_file``,
in the (proxy) minion configuration file or pillar.
Configuration example:
.. code-block:: yaml
textfsm_platform_grain: vendor
textfsm_path: salt://textfsm/
textfsm_platform_column_name: Vendor
And the CLI usage becomes as simple as:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example
Usgae inside a Jinja template:
.. code-block:: jinja
{%- set command = 'sh ver' -%}
{%- set output = salt.net.cli(command) -%}
{%- set textfsm_extract = salt.textfsm.index(command, output=output) -%}
'''
ret = {
'out': None,
'result': False,
'comment': ''
}
if not HAS_CLITABLE:
ret['comment'] = 'TextFSM doesnt seem that has clitable embedded.'
log.error(ret['comment'])
return ret
if not platform:
platform_grain_name = __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', platform_grain_name)
if platform_grain_name:
log.debug('Using the %s grain to identify the platform name', platform_grain_name)
platform = __grains__.get(platform_grain_name)
if not platform:
ret['comment'] = 'Unable to identify the platform name using the {} grain.'.format(platform_grain_name)
return ret
log.info('Using platform: %s', platform)
else:
ret['comment'] = 'No platform specified, no platform grain identifier configured.'
log.error(ret['comment'])
return ret
if not textfsm_path:
log.debug('No TextFSM templates path specified, trying to look into the opts and pillar')
textfsm_path = __opts__.get('textfsm_path') or __pillar__.get('textfsm_path')
if not textfsm_path:
ret['comment'] = 'No TextFSM templates path specified. Please configure in opts/pillar/function args.'
log.error(ret['comment'])
return ret
log.debug('Using the saltenv: %s', saltenv)
log.debug('Caching %s using the Salt fileserver', textfsm_path)
textfsm_cachedir_ret = __salt__['cp.cache_dir'](textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Cache fun return:')
log.debug(textfsm_cachedir_ret)
if not textfsm_cachedir_ret:
ret['comment'] = 'Unable to fetch from {}. Is the TextFSM path correctly specified?'.format(textfsm_path)
log.error(ret['comment'])
return ret
textfsm_cachedir = os.path.dirname(textfsm_cachedir_ret[0]) # first item
index_file = __opts__.get('textfsm_index_file') or __pillar__.get('textfsm_index_file', 'index')
index_file_path = os.path.join(textfsm_cachedir, index_file)
log.debug('Using the cached index file: %s', index_file_path)
log.debug('TextFSM templates cached under: %s', textfsm_cachedir)
textfsm_obj = clitable.CliTable(index_file_path, textfsm_cachedir)
attrs = {
'Command': command
}
platform_column_name = __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.info('Using the TextFSM platform idenfiticator: %s', platform_column_name)
attrs[platform_column_name] = platform
log.debug('Processing the TextFSM index file using the attributes: %s', attrs)
if not output and output_file:
log.debug('Processing the output from %s', output_file)
output = __salt__['cp.get_file_str'](output_file, saltenv=saltenv)
if output is False:
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(output_file)
log.error(ret['comment'])
return ret
if not output:
ret['comment'] = 'Please specify a valid output text or file'
log.error(ret['comment'])
return ret
log.debug('Processing the raw text:')
log.debug(output)
try:
# Parse output through template
textfsm_obj.ParseCmd(output, attrs)
ret['out'] = _clitable_to_dict(textfsm_obj, textfsm_obj)
ret['result'] = True
except clitable.CliTableError as cterr:
log.error('Unable to proces the CliTable', exc_info=True)
ret['comment'] = 'Unable to process the output: {}'.format(cterr)
return ret
|
saltstack/salt
|
salt/modules/textfsm_mod.py
|
index
|
python
|
def index(command,
platform=None,
platform_grain_name=None,
platform_column_name=None,
output=None,
output_file=None,
textfsm_path=None,
index_file=None,
saltenv='base',
include_empty=False,
include_pat=None,
exclude_pat=None):
'''
Dynamically identify the template required to extract the
information from the unstructured raw text.
The output has the same structure as the ``extract`` execution
function, the difference being that ``index`` is capable
to identify what template to use, based on the platform
details and the ``command``.
command
The command executed on the device, to get the output.
platform
The platform name, as defined in the TextFSM index file.
.. note::
For ease of use, it is recommended to define the TextFSM
indexfile with values that can be matches using the grains.
platform_grain_name
The name of the grain used to identify the platform name
in the TextFSM index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
.. note::
This option is ignored when ``platform`` is specified.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
output
The raw output from the device, to be parsed
and extract the structured data.
output_file
The path to a file that contains the raw output from the device,
used to extract the structured data.
This option supports the usual Salt-specific schemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``, ``s3://``, ``swift://``.
textfsm_path
The path where the TextFSM templates can be found. This can be either
absolute path on the server, either specified using the following URL
schemes: ``file://``, ``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
include_empty: ``False``
Include empty files under the ``textfsm_path``.
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' platform=Juniper output_file=salt://textfsm/juniper_version_example textfsm_path=salt://textfsm/
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=ftp://textfsm/ platform_column_name=Vendor
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=https://some-server/textfsm/ platform_column_name=Vendor platform_grain_name=vendor
TextFSM index file example:
``salt://textfsm/index``
.. code-block:: text
Template, Hostname, Vendor, Command
juniper_version_template, .*, Juniper, sh[[ow]] ve[[rsion]]
The usage can be simplified,
by defining (some of) the following options: ``textfsm_platform_grain``,
``textfsm_path``, ``textfsm_platform_column_name``, or ``textfsm_index_file``,
in the (proxy) minion configuration file or pillar.
Configuration example:
.. code-block:: yaml
textfsm_platform_grain: vendor
textfsm_path: salt://textfsm/
textfsm_platform_column_name: Vendor
And the CLI usage becomes as simple as:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example
Usgae inside a Jinja template:
.. code-block:: jinja
{%- set command = 'sh ver' -%}
{%- set output = salt.net.cli(command) -%}
{%- set textfsm_extract = salt.textfsm.index(command, output=output) -%}
'''
ret = {
'out': None,
'result': False,
'comment': ''
}
if not HAS_CLITABLE:
ret['comment'] = 'TextFSM doesnt seem that has clitable embedded.'
log.error(ret['comment'])
return ret
if not platform:
platform_grain_name = __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', platform_grain_name)
if platform_grain_name:
log.debug('Using the %s grain to identify the platform name', platform_grain_name)
platform = __grains__.get(platform_grain_name)
if not platform:
ret['comment'] = 'Unable to identify the platform name using the {} grain.'.format(platform_grain_name)
return ret
log.info('Using platform: %s', platform)
else:
ret['comment'] = 'No platform specified, no platform grain identifier configured.'
log.error(ret['comment'])
return ret
if not textfsm_path:
log.debug('No TextFSM templates path specified, trying to look into the opts and pillar')
textfsm_path = __opts__.get('textfsm_path') or __pillar__.get('textfsm_path')
if not textfsm_path:
ret['comment'] = 'No TextFSM templates path specified. Please configure in opts/pillar/function args.'
log.error(ret['comment'])
return ret
log.debug('Using the saltenv: %s', saltenv)
log.debug('Caching %s using the Salt fileserver', textfsm_path)
textfsm_cachedir_ret = __salt__['cp.cache_dir'](textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Cache fun return:')
log.debug(textfsm_cachedir_ret)
if not textfsm_cachedir_ret:
ret['comment'] = 'Unable to fetch from {}. Is the TextFSM path correctly specified?'.format(textfsm_path)
log.error(ret['comment'])
return ret
textfsm_cachedir = os.path.dirname(textfsm_cachedir_ret[0]) # first item
index_file = __opts__.get('textfsm_index_file') or __pillar__.get('textfsm_index_file', 'index')
index_file_path = os.path.join(textfsm_cachedir, index_file)
log.debug('Using the cached index file: %s', index_file_path)
log.debug('TextFSM templates cached under: %s', textfsm_cachedir)
textfsm_obj = clitable.CliTable(index_file_path, textfsm_cachedir)
attrs = {
'Command': command
}
platform_column_name = __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.info('Using the TextFSM platform idenfiticator: %s', platform_column_name)
attrs[platform_column_name] = platform
log.debug('Processing the TextFSM index file using the attributes: %s', attrs)
if not output and output_file:
log.debug('Processing the output from %s', output_file)
output = __salt__['cp.get_file_str'](output_file, saltenv=saltenv)
if output is False:
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(output_file)
log.error(ret['comment'])
return ret
if not output:
ret['comment'] = 'Please specify a valid output text or file'
log.error(ret['comment'])
return ret
log.debug('Processing the raw text:')
log.debug(output)
try:
# Parse output through template
textfsm_obj.ParseCmd(output, attrs)
ret['out'] = _clitable_to_dict(textfsm_obj, textfsm_obj)
ret['result'] = True
except clitable.CliTableError as cterr:
log.error('Unable to proces the CliTable', exc_info=True)
ret['comment'] = 'Unable to process the output: {}'.format(cterr)
return ret
|
Dynamically identify the template required to extract the
information from the unstructured raw text.
The output has the same structure as the ``extract`` execution
function, the difference being that ``index`` is capable
to identify what template to use, based on the platform
details and the ``command``.
command
The command executed on the device, to get the output.
platform
The platform name, as defined in the TextFSM index file.
.. note::
For ease of use, it is recommended to define the TextFSM
indexfile with values that can be matches using the grains.
platform_grain_name
The name of the grain used to identify the platform name
in the TextFSM index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
.. note::
This option is ignored when ``platform`` is specified.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
output
The raw output from the device, to be parsed
and extract the structured data.
output_file
The path to a file that contains the raw output from the device,
used to extract the structured data.
This option supports the usual Salt-specific schemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``, ``s3://``, ``swift://``.
textfsm_path
The path where the TextFSM templates can be found. This can be either
absolute path on the server, either specified using the following URL
schemes: ``file://``, ``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
include_empty: ``False``
Include empty files under the ``textfsm_path``.
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' platform=Juniper output_file=salt://textfsm/juniper_version_example textfsm_path=salt://textfsm/
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=ftp://textfsm/ platform_column_name=Vendor
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example textfsm_path=https://some-server/textfsm/ platform_column_name=Vendor platform_grain_name=vendor
TextFSM index file example:
``salt://textfsm/index``
.. code-block:: text
Template, Hostname, Vendor, Command
juniper_version_template, .*, Juniper, sh[[ow]] ve[[rsion]]
The usage can be simplified,
by defining (some of) the following options: ``textfsm_platform_grain``,
``textfsm_path``, ``textfsm_platform_column_name``, or ``textfsm_index_file``,
in the (proxy) minion configuration file or pillar.
Configuration example:
.. code-block:: yaml
textfsm_platform_grain: vendor
textfsm_path: salt://textfsm/
textfsm_platform_column_name: Vendor
And the CLI usage becomes as simple as:
.. code-block:: bash
salt '*' textfsm.index 'sh ver' output_file=salt://textfsm/juniper_version_example
Usgae inside a Jinja template:
.. code-block:: jinja
{%- set command = 'sh ver' -%}
{%- set output = salt.net.cli(command) -%}
{%- set textfsm_extract = salt.textfsm.index(command, output=output) -%}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/textfsm_mod.py#L228-L459
|
[
"def _clitable_to_dict(objects, fsm_handler):\n '''\n Converts TextFSM cli_table object to list of dictionaries.\n '''\n objs = []\n log.debug('Cli Table:')\n log.debug(objects)\n log.debug('FSM handler:')\n log.debug(fsm_handler)\n for row in objects:\n temp_dict = {}\n for index, element in enumerate(row):\n temp_dict[fsm_handler.header[index].lower()] = element\n objs.append(temp_dict)\n log.debug('Extraction result:')\n log.debug(objs)\n return objs\n"
] |
# -*- coding: utf-8 -*-
'''
TextFSM
=======
.. versionadded:: 2018.3.0
Execution module that processes plain text and extracts data
using TextFSM templates. The output is presented in JSON serializable
data, and can be easily re-used in other modules, or directly
inside the renderer (Jinja, Mako, Genshi, etc.).
:depends: - textfsm Python library
.. note::
For Python 2/3 compatibility, it is more recommended to
install the ``jtextfsm`` library: ``pip install jtextfsm``.
'''
from __future__ import absolute_import
# Import python libs
import os
import logging
# Import third party modules
try:
import textfsm
HAS_TEXTFSM = True
except ImportError:
HAS_TEXTFSM = False
try:
import clitable
HAS_CLITABLE = True
except ImportError:
HAS_CLITABLE = False
try:
from salt.utils.files import fopen
except ImportError:
from salt.utils import fopen
log = logging.getLogger(__name__)
__virtualname__ = 'textfsm'
__proxyenabled__ = ['*']
def __virtual__():
'''
Only load this execution module if TextFSM is installed.
'''
if HAS_TEXTFSM:
return __virtualname__
return (False, 'The textfsm execution module failed to load: requires the textfsm library.')
def _clitable_to_dict(objects, fsm_handler):
'''
Converts TextFSM cli_table object to list of dictionaries.
'''
objs = []
log.debug('Cli Table:')
log.debug(objects)
log.debug('FSM handler:')
log.debug(fsm_handler)
for row in objects:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[fsm_handler.header[index].lower()] = element
objs.append(temp_dict)
log.debug('Extraction result:')
log.debug(objs)
return objs
def extract(template_path, raw_text=None, raw_text_file=None, saltenv='base'):
r'''
Extracts the data entities from the unstructured
raw text sent as input and returns the data
mapping, processing using the TextFSM template.
template_path
The path to the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
raw_text: ``None``
The unstructured text to be parsed.
raw_text_file: ``None``
Text file to read, having the raw text to be parsed using the TextFSM template.
Supports the same URL schemes as the ``template_path`` argument.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``template_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' textfsm.extract salt://textfsm/juniper_version_template raw_text_file=s3://junos_ver.txt
salt '*' textfsm.extract http://some-server/textfsm/juniper_version_template raw_text='Hostname: router.abc ... snip ...'
Jinja template example:
.. code-block:: jinja
{%- set raw_text = 'Hostname: router.abc ... snip ...' -%}
{%- set textfsm_extract = salt.textfsm.extract('https://some-server/textfsm/juniper_version_template', raw_text) -%}
Raw text example:
.. code-block:: text
Hostname: router.abc
Model: mx960
JUNOS Base OS boot [9.1S3.5]
JUNOS Base OS Software Suite [9.1S3.5]
JUNOS Kernel Software Suite [9.1S3.5]
JUNOS Crypto Software Suite [9.1S3.5]
JUNOS Packet Forwarding Engine Support (M/T Common) [9.1S3.5]
JUNOS Packet Forwarding Engine Support (MX Common) [9.1S3.5]
JUNOS Online Documentation [9.1S3.5]
JUNOS Routing Software Suite [9.1S3.5]
TextFSM Example:
.. code-block:: text
Value Chassis (\S+)
Value Required Model (\S+)
Value Boot (.*)
Value Base (.*)
Value Kernel (.*)
Value Crypto (.*)
Value Documentation (.*)
Value Routing (.*)
Start
# Support multiple chassis systems.
^\S+:$$ -> Continue.Record
^${Chassis}:$$
^Model: ${Model}
^JUNOS Base OS boot \[${Boot}\]
^JUNOS Software Release \[${Base}\]
^JUNOS Base OS Software Suite \[${Base}\]
^JUNOS Kernel Software Suite \[${Kernel}\]
^JUNOS Crypto Software Suite \[${Crypto}\]
^JUNOS Online Documentation \[${Documentation}\]
^JUNOS Routing Software Suite \[${Routing}\]
Output example:
.. code-block:: json
{
"comment": "",
"result": true,
"out": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
'''
ret = {
'result': False,
'comment': '',
'out': None
}
log.debug('Using the saltenv: %s', saltenv)
log.debug('Caching %s using the Salt fileserver', template_path)
tpl_cached_path = __salt__['cp.cache_file'](template_path, saltenv=saltenv)
if tpl_cached_path is False:
ret['comment'] = 'Unable to read the TextFSM template from {}'.format(template_path)
log.error(ret['comment'])
return ret
try:
log.debug('Reading TextFSM template from cache path: %s', tpl_cached_path)
# Disabling pylint W8470 to nto complain about fopen.
# Unfortunately textFSM needs the file handle rather than the content...
# pylint: disable=W8470
tpl_file_handle = fopen(tpl_cached_path, 'r')
# pylint: disable=W8470
log.debug(tpl_file_handle.read())
tpl_file_handle.seek(0) # move the object position back at the top of the file
fsm_handler = textfsm.TextFSM(tpl_file_handle)
except textfsm.TextFSMTemplateError as tfte:
log.error('Unable to parse the TextFSM template', exc_info=True)
ret['comment'] = 'Unable to parse the TextFSM template from {}: {}. Please check the logs.'.format(
template_path, tfte)
return ret
if not raw_text and raw_text_file:
log.debug('Trying to read the raw input from %s', raw_text_file)
raw_text = __salt__['cp.get_file_str'](raw_text_file, saltenv=saltenv)
if raw_text is False:
ret['comment'] = 'Unable to read from {}. Please specify a valid input file or text.'.format(raw_text_file)
log.error(ret['comment'])
return ret
if not raw_text:
ret['comment'] = 'Please specify a valid input file or text.'
log.error(ret['comment'])
return ret
log.debug('Processing the raw text:')
log.debug(raw_text)
objects = fsm_handler.ParseText(raw_text)
ret['out'] = _clitable_to_dict(objects, fsm_handler)
ret['result'] = True
return ret
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
read_body
|
python
|
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
|
Pull the body from the request and return it
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L182-L189
| null |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
get_json
|
python
|
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
|
Return the request body as JSON
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L192-L203
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def read_body(environ):\n '''\n Pull the body from the request and return it\n '''\n length = environ.get('CONTENT_LENGTH', '0')\n length = 0 if length == '' else int(length)\n\n return environ['wsgi.input'].read(length)\n"
] |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
get_headers
|
python
|
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
|
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L206-L218
| null |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
run_chunk
|
python
|
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
|
Expects a list of lowstate dictionaries that are executed and returned in
order
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L221-L229
| null |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
dispatch
|
python
|
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
|
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L232-L246
|
[
"def get_json(environ):\n '''\n Return the request body as JSON\n '''\n content_type = environ.get('CONTENT_TYPE', '')\n if content_type != 'application/json':\n raise HTTPError(406, 'JSON required')\n\n try:\n return salt.utils.json.loads(read_body(environ))\n except ValueError as exc:\n raise HTTPError(400, exc)\n",
"def run_chunk(environ, lowstate):\n '''\n Expects a list of lowstate dictionaries that are executed and returned in\n order\n '''\n client = environ['SALT_APIClient']\n\n for chunk in lowstate:\n yield client.run(chunk)\n"
] |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
saltenviron
|
python
|
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
|
Make Salt's opts dict and the APIClient available in the WSGI environ
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L249-L259
|
[
"def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):\n '''\n Load Master configuration data\n\n Usage:\n\n .. code-block:: python\n\n import salt.config\n master_opts = salt.config.client_config('/etc/salt/master')\n\n Returns a dictionary of the Salt Master configuration file with necessary\n options needed to communicate with a locally-running Salt Master daemon.\n This function searches for client specific configurations and adds them to\n the data from the master configuration.\n\n This is useful for master-side operations like\n :py:class:`~salt.client.LocalClient`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n xdg_dir = salt.utils.xdg.xdg_config_dir()\n if os.path.isdir(xdg_dir):\n client_config_dir = xdg_dir\n saltrc_config_file = 'saltrc'\n else:\n client_config_dir = os.path.expanduser('~')\n saltrc_config_file = '.saltrc'\n\n # Get the token file path from the provided defaults. If not found, specify\n # our own, sane, default\n opts = {\n 'token_file': defaults.get(\n 'token_file',\n os.path.join(client_config_dir, 'salt_token')\n )\n }\n # Update options with the master configuration, either from the provided\n # path, salt's defaults or provided defaults\n opts.update(\n master_config(path, defaults=defaults)\n )\n # Update with the users salt dot file or with the environment variable\n saltrc_config = os.path.join(client_config_dir, saltrc_config_file)\n opts.update(\n load_config(\n saltrc_config,\n env_var,\n saltrc_config\n )\n )\n # Make sure we have a proper and absolute path to the token file\n if 'token_file' in opts:\n opts['token_file'] = os.path.abspath(\n os.path.expanduser(\n opts['token_file']\n )\n )\n # If the token file exists, read and store the contained token\n if os.path.isfile(opts['token_file']):\n # Make sure token is still valid\n expire = opts.get('token_expire', 43200)\n if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):\n with salt.utils.files.fopen(opts['token_file']) as fp_:\n opts['token'] = fp_.read().strip()\n # On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost\n if opts['interface'] == '0.0.0.0':\n opts['interface'] = '127.0.0.1'\n\n # Make sure the master_uri is set\n if 'master_uri' not in opts:\n opts['master_uri'] = 'tcp://{ip}:{port}'.format(\n ip=salt.utils.zeromq.ip_bracket(opts['interface']),\n port=opts['ret_port']\n )\n\n # Return the client options\n _validate_opts(opts)\n return opts\n"
] |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
application
|
python
|
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
|
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L262-L295
|
[
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def dispatch(environ):\n '''\n Do any path/method dispatching here and return a JSON-serializable data\n structure appropriate for the response\n '''\n method = environ['REQUEST_METHOD'].upper()\n\n if method == 'GET':\n return (\"They found me. I don't know how, but they found me. \"\n \"Run for it, Marty!\")\n elif method == 'POST':\n data = get_json(environ)\n return run_chunk(environ, data)\n else:\n raise HTTPError(405, 'Method Not Allowed')\n",
"def get_headers(data, extra_headers=None):\n '''\n Takes the response data as well as any additional headers and returns a\n tuple of tuples of headers suitable for passing to start_response()\n '''\n response_headers = {\n 'Content-Length': str(len(data)),\n }\n\n if extra_headers:\n response_headers.update(extra_headers)\n\n return list(response_headers.items())\n",
"def saltenviron(environ):\n '''\n Make Salt's opts dict and the APIClient available in the WSGI environ\n '''\n if '__opts__' not in locals():\n import salt.config\n __opts__ = salt.config.client_config(\n os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))\n\n environ['SALT_OPTS'] = __opts__\n environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)\n"
] |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/netapi/rest_wsgi.py
|
start
|
python
|
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1)
mod_opts = __opts__.get(__virtualname__, {})
# pylint: disable=C0103
httpd = make_server('localhost', mod_opts['port'], application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
raise SystemExit(0)
|
Start simple_server()
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_wsgi.py#L308-L329
|
[
"def __virtual__():\n mod_opts = __opts__.get(__virtualname__, {})\n\n if 'port' in mod_opts:\n return __virtualname__\n\n return False\n",
"def get_opts():\n '''\n Return the Salt master config as __opts__\n '''\n import salt.config\n\n return salt.config.client_config(\n os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))\n"
] |
# encoding: utf-8
'''
A minimalist REST API for Salt
==============================
This ``rest_wsgi`` module provides a no-frills REST interface for sending
commands to the Salt master. There are no dependencies.
Extra care must be taken when deploying this module into production. Please
read this documentation in entirety.
All authentication is done through Salt's :ref:`external auth <acl-eauth>`
system.
Usage
=====
* All requests must be sent to the root URL (``/``).
* All requests must be sent as a POST request with JSON content in the request
body.
* All responses are in JSON.
.. seealso:: :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>`
The :py:mod:`rest_cherrypy <salt.netapi.rest_cherrypy.app>` module is
more full-featured, production-ready, and has builtin security features.
Deployment
==========
The ``rest_wsgi`` netapi module is a standard Python WSGI app. It can be
deployed one of two ways.
Using a WSGI-compliant web server
---------------------------------
This module may be run via any WSGI-compliant production server such as Apache
with mod_wsgi or Nginx with FastCGI.
It is strongly recommended that this app be used with a server that supports
HTTPS encryption since raw Salt authentication credentials must be sent with
every request. Any apps that access Salt through this interface will need to
manually manage authentication credentials (either username and password or a
Salt token). Tread carefully.
:program:`salt-api` using a development-only server
---------------------------------------------------
If run directly via the salt-api daemon it uses the `wsgiref.simple_server()`__
that ships in the Python standard library. This is a single-threaded server
that is intended for testing and development. **This server does not use
encryption**; please note that raw Salt authentication credentials must be sent
with every HTTP request.
**Running this module via salt-api is not recommended!**
In order to start this module via the ``salt-api`` daemon the following must be
put into the Salt master config::
rest_wsgi:
port: 8001
.. __: http://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server
Usage examples
==============
.. http:post:: /
**Example request** for a basic ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
**Example request** for an asynchronous ``test.ping``::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"local_async","tgt":"*","fun":"test.ping"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 103
Content-Type: application/json
{"return": [{"jid": "20130412192112593739", "minions": ["ms--4", "ms--3", "ms--2", "ms--1", "ms--0"]}]}
**Example request** for looking up a job ID::
% curl -sS -i \\
-H 'Content-Type: application/json' \\
-d '[{"eauth":"pam","username":"saltdev","password":"saltdev","client":"runner","fun":"jobs.lookup_jid","jid":"20130412192112593739"}]' localhost:8001
**Example response**:
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 89
Content-Type: application/json
{"return": [{"ms--4": true, "ms--3": true, "ms--2": true, "ms--1": true, "ms--0": true}]}
:form lowstate: A list of lowstate data appropriate for the
:ref:`client <client-apis>` interface you are calling.
:status 200: success
:status 401: authentication required
'''
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
# Import salt libs
import salt
import salt.netapi
import salt.utils.json
# HTTP response codes to response headers map
H = {
200: '200 OK',
400: '400 BAD REQUEST',
401: '401 UNAUTHORIZED',
404: '404 NOT FOUND',
405: '405 METHOD NOT ALLOWED',
406: '406 NOT ACCEPTABLE',
500: '500 INTERNAL SERVER ERROR',
}
__virtualname__ = 'rest_wsgi'
logger = logging.getLogger(__virtualname__)
def __virtual__():
mod_opts = __opts__.get(__virtualname__, {})
if 'port' in mod_opts:
return __virtualname__
return False
class HTTPError(Exception):
'''
A custom exception that can take action based on an HTTP error code
'''
def __init__(self, code, message):
self.code = code
Exception.__init__(self, '{0}: {1}'.format(code, message))
def mkdir_p(path):
'''
mkdir -p
http://stackoverflow.com/a/600612/127816
'''
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def read_body(environ):
'''
Pull the body from the request and return it
'''
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
return environ['wsgi.input'].read(length)
def get_json(environ):
'''
Return the request body as JSON
'''
content_type = environ.get('CONTENT_TYPE', '')
if content_type != 'application/json':
raise HTTPError(406, 'JSON required')
try:
return salt.utils.json.loads(read_body(environ))
except ValueError as exc:
raise HTTPError(400, exc)
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_headers.update(extra_headers)
return list(response_headers.items())
def run_chunk(environ, lowstate):
'''
Expects a list of lowstate dictionaries that are executed and returned in
order
'''
client = environ['SALT_APIClient']
for chunk in lowstate:
yield client.run(chunk)
def dispatch(environ):
'''
Do any path/method dispatching here and return a JSON-serializable data
structure appropriate for the response
'''
method = environ['REQUEST_METHOD'].upper()
if method == 'GET':
return ("They found me. I don't know how, but they found me. "
"Run for it, Marty!")
elif method == 'POST':
data = get_json(environ)
return run_chunk(environ, data)
else:
raise HTTPError(405, 'Method Not Allowed')
def saltenviron(environ):
'''
Make Salt's opts dict and the APIClient available in the WSGI environ
'''
if '__opts__' not in locals():
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
environ['SALT_OPTS'] = __opts__
environ['SALT_APIClient'] = salt.netapi.NetapiClient(__opts__)
def application(environ, start_response):
'''
Process the request and return a JSON response. Catch errors and return the
appropriate HTTP code.
'''
# Instantiate APIClient once for the whole app
saltenviron(environ)
# Call the dispatcher
try:
resp = list(dispatch(environ))
code = 200
except HTTPError as exc:
code = exc.code
resp = str(exc)
except salt.exceptions.EauthAuthenticationError as exc:
code = 401
resp = str(exc)
except Exception as exc:
code = 500
resp = str(exc)
# Convert the response to JSON
try:
ret = salt.utils.json.dumps({'return': resp})
except TypeError as exc:
code = 500
ret = str(exc) # future lint: disable=blacklisted-function
# Return the response
start_response(H[code], get_headers(ret, {
'Content-Type': 'application/json',
}))
return (ret,)
def get_opts():
'''
Return the Salt master config as __opts__
'''
import salt.config
return salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
if __name__ == '__main__':
start()
|
saltstack/salt
|
salt/utils/itertools.py
|
split
|
python
|
def split(orig, sep=None):
'''
Generator function for iterating through large strings, particularly useful
as a replacement for str.splitlines().
See http://stackoverflow.com/a/3865367
'''
exp = re.compile(r'\s+' if sep is None else re.escape(sep))
pos = 0
length = len(orig)
while True:
match = exp.search(orig, pos)
if not match:
if pos < length or sep is not None:
val = orig[pos:]
if val:
# Only yield a value if the slice was not an empty string,
# because if it is then we've reached the end. This keeps
# us from yielding an extra blank value at the end.
yield val
break
if pos < match.start() or sep is not None:
yield orig[pos:match.start()]
pos = match.end()
|
Generator function for iterating through large strings, particularly useful
as a replacement for str.splitlines().
See http://stackoverflow.com/a/3865367
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/itertools.py#L15-L38
| null |
# -*- coding: utf-8 -*-
'''
Helpful generators and other tools
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import fnmatch
import re
# Import Salt libs
import salt.utils.files
def read_file(fh_, chunk_size=1048576):
'''
Generator that reads chunk_size bytes at a time from a file/filehandle and
yields it.
'''
try:
if chunk_size != int(chunk_size):
raise ValueError
except ValueError:
raise ValueError('chunk_size must be an integer')
try:
while True:
try:
chunk = fh_.read(chunk_size)
except AttributeError:
# Open the file and re-attempt the read
fh_ = salt.utils.files.fopen(fh_, 'rb') # pylint: disable=W8470
chunk = fh_.read(chunk_size)
if not chunk:
break
yield chunk
finally:
try:
fh_.close()
except AttributeError:
pass
def fnmatch_multiple(candidates, pattern):
'''
Convenience function which runs fnmatch.fnmatch() on each element of passed
iterable. The first matching candidate is returned, or None if there is no
matching candidate.
'''
# Make sure that candidates is iterable to avoid a TypeError when we try to
# iterate over its items.
try:
candidates_iter = iter(candidates)
except TypeError:
return None
for candidate in candidates_iter:
try:
if fnmatch.fnmatch(candidate, pattern):
return candidate
except TypeError:
pass
return None
|
saltstack/salt
|
salt/utils/itertools.py
|
read_file
|
python
|
def read_file(fh_, chunk_size=1048576):
'''
Generator that reads chunk_size bytes at a time from a file/filehandle and
yields it.
'''
try:
if chunk_size != int(chunk_size):
raise ValueError
except ValueError:
raise ValueError('chunk_size must be an integer')
try:
while True:
try:
chunk = fh_.read(chunk_size)
except AttributeError:
# Open the file and re-attempt the read
fh_ = salt.utils.files.fopen(fh_, 'rb') # pylint: disable=W8470
chunk = fh_.read(chunk_size)
if not chunk:
break
yield chunk
finally:
try:
fh_.close()
except AttributeError:
pass
|
Generator that reads chunk_size bytes at a time from a file/filehandle and
yields it.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/itertools.py#L41-L66
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
Helpful generators and other tools
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import fnmatch
import re
# Import Salt libs
import salt.utils.files
def split(orig, sep=None):
'''
Generator function for iterating through large strings, particularly useful
as a replacement for str.splitlines().
See http://stackoverflow.com/a/3865367
'''
exp = re.compile(r'\s+' if sep is None else re.escape(sep))
pos = 0
length = len(orig)
while True:
match = exp.search(orig, pos)
if not match:
if pos < length or sep is not None:
val = orig[pos:]
if val:
# Only yield a value if the slice was not an empty string,
# because if it is then we've reached the end. This keeps
# us from yielding an extra blank value at the end.
yield val
break
if pos < match.start() or sep is not None:
yield orig[pos:match.start()]
pos = match.end()
def fnmatch_multiple(candidates, pattern):
'''
Convenience function which runs fnmatch.fnmatch() on each element of passed
iterable. The first matching candidate is returned, or None if there is no
matching candidate.
'''
# Make sure that candidates is iterable to avoid a TypeError when we try to
# iterate over its items.
try:
candidates_iter = iter(candidates)
except TypeError:
return None
for candidate in candidates_iter:
try:
if fnmatch.fnmatch(candidate, pattern):
return candidate
except TypeError:
pass
return None
|
saltstack/salt
|
salt/utils/itertools.py
|
fnmatch_multiple
|
python
|
def fnmatch_multiple(candidates, pattern):
'''
Convenience function which runs fnmatch.fnmatch() on each element of passed
iterable. The first matching candidate is returned, or None if there is no
matching candidate.
'''
# Make sure that candidates is iterable to avoid a TypeError when we try to
# iterate over its items.
try:
candidates_iter = iter(candidates)
except TypeError:
return None
for candidate in candidates_iter:
try:
if fnmatch.fnmatch(candidate, pattern):
return candidate
except TypeError:
pass
return None
|
Convenience function which runs fnmatch.fnmatch() on each element of passed
iterable. The first matching candidate is returned, or None if there is no
matching candidate.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/itertools.py#L69-L88
| null |
# -*- coding: utf-8 -*-
'''
Helpful generators and other tools
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import fnmatch
import re
# Import Salt libs
import salt.utils.files
def split(orig, sep=None):
'''
Generator function for iterating through large strings, particularly useful
as a replacement for str.splitlines().
See http://stackoverflow.com/a/3865367
'''
exp = re.compile(r'\s+' if sep is None else re.escape(sep))
pos = 0
length = len(orig)
while True:
match = exp.search(orig, pos)
if not match:
if pos < length or sep is not None:
val = orig[pos:]
if val:
# Only yield a value if the slice was not an empty string,
# because if it is then we've reached the end. This keeps
# us from yielding an extra blank value at the end.
yield val
break
if pos < match.start() or sep is not None:
yield orig[pos:match.start()]
pos = match.end()
def read_file(fh_, chunk_size=1048576):
'''
Generator that reads chunk_size bytes at a time from a file/filehandle and
yields it.
'''
try:
if chunk_size != int(chunk_size):
raise ValueError
except ValueError:
raise ValueError('chunk_size must be an integer')
try:
while True:
try:
chunk = fh_.read(chunk_size)
except AttributeError:
# Open the file and re-attempt the read
fh_ = salt.utils.files.fopen(fh_, 'rb') # pylint: disable=W8470
chunk = fh_.read(chunk_size)
if not chunk:
break
yield chunk
finally:
try:
fh_.close()
except AttributeError:
pass
|
saltstack/salt
|
salt/utils/docker/__init__.py
|
translate_input
|
python
|
def translate_input(translator,
skip_translate=None,
ignore_collisions=False,
validate_ip_addrs=True,
**kwargs):
'''
Translate CLI/SLS input into the format the API expects. The ``translator``
argument must be a module containing translation functions, within
salt.utils.docker.translate. A ``skip_translate`` kwarg can be passed to
control which arguments are translated. It can be either a comma-separated
list or an iterable containing strings (e.g. a list or tuple), and members
of that tuple will have their translation skipped. Optionally,
skip_translate can be set to True to skip *all* translation.
'''
kwargs = copy.deepcopy(salt.utils.args.clean_kwargs(**kwargs))
invalid = {}
collisions = []
if skip_translate is True:
# Skip all translation
return kwargs
else:
if not skip_translate:
skip_translate = ()
else:
try:
skip_translate = _split(skip_translate)
except AttributeError:
pass
if not hasattr(skip_translate, '__iter__'):
log.error('skip_translate is not an iterable, ignoring')
skip_translate = ()
try:
# Using list(kwargs) here because if there are any invalid arguments we
# will be popping them from the kwargs.
for key in list(kwargs):
real_key = translator.ALIASES.get(key, key)
if real_key in skip_translate:
continue
# ipam_pools is designed to be passed as a list of actual
# dictionaries, but if each of the dictionaries passed has a single
# element, it will be incorrectly repacked.
if key != 'ipam_pools' and salt.utils.data.is_dictlist(kwargs[key]):
kwargs[key] = salt.utils.data.repack_dictlist(kwargs[key])
try:
kwargs[key] = getattr(translator, real_key)(
kwargs[key],
validate_ip_addrs=validate_ip_addrs,
skip_translate=skip_translate)
except AttributeError:
log.debug('No translation function for argument \'%s\'', key)
continue
except SaltInvocationError as exc:
kwargs.pop(key)
invalid[key] = exc.strerror
try:
translator._merge_keys(kwargs)
except AttributeError:
pass
# Convert CLI versions of commands to their docker-py counterparts
for key in translator.ALIASES:
if key in kwargs:
new_key = translator.ALIASES[key]
value = kwargs.pop(key)
if new_key in kwargs:
collisions.append(new_key)
else:
kwargs[new_key] = value
try:
translator._post_processing(kwargs, skip_translate, invalid)
except AttributeError:
pass
except Exception as exc:
error_message = exc.__str__()
log.error(
'Error translating input: \'%s\'', error_message, exc_info=True)
else:
error_message = None
error_data = {}
if error_message is not None:
error_data['error_message'] = error_message
if invalid:
error_data['invalid'] = invalid
if collisions and not ignore_collisions:
for item in collisions:
error_data.setdefault('collisions', []).append(
'\'{0}\' is an alias for \'{1}\', they cannot both be used'
.format(translator.ALIASES_REVMAP[item], item)
)
if error_data:
raise CommandExecutionError(
'Failed to translate input', info=error_data)
return kwargs
|
Translate CLI/SLS input into the format the API expects. The ``translator``
argument must be a module containing translation functions, within
salt.utils.docker.translate. A ``skip_translate`` kwarg can be passed to
control which arguments are translated. It can be either a comma-separated
list or an iterable containing strings (e.g. a list or tuple), and members
of that tuple will have their translation skipped. Optionally,
skip_translate can be set to True to skip *all* translation.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/__init__.py#L172-L273
|
[
"def split(item, sep=',', maxsplit=-1):\n return [x.strip() for x in item.split(sep, maxsplit)]\n",
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def is_dictlist(data):\n '''\n Returns True if data is a list of one-element dicts (as found in many SLS\n schemas), otherwise returns False\n '''\n if isinstance(data, list):\n for element in data:\n if isinstance(element, dict):\n if len(element) != 1:\n return False\n else:\n return False\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Common logic used by the docker state and execution module
This module contains logic to accommodate docker/salt CLI usage, as well as
input as formatted by states.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.docker.translate
from salt.utils.docker.translate.helpers import split as _split
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.utils.args import get_function_argspec as _argspec
# Import 3rd-party libs
from salt.ext import six
try:
import docker
HAS_DOCKER_PY = True
except ImportError:
HAS_DOCKER_PY = False
# These next two imports are only necessary to have access to the needed
# functions so that we can get argspecs for the container config, host config,
# and networking config (see the get_client_args() function).
try:
import docker.types
except ImportError:
pass
try:
import docker.utils
except ImportError:
pass
NOTSET = object()
# Default timeout as of docker-py 1.0.0
CLIENT_TIMEOUT = 60
# Timeout for stopping the container, before a kill is invoked
SHUTDOWN_TIMEOUT = 10
log = logging.getLogger(__name__)
def get_client_args(limit=None):
if not HAS_DOCKER_PY:
raise CommandExecutionError('docker Python module not imported')
limit = salt.utils.args.split_input(limit or [])
ret = {}
if not limit or any(x in limit for x in
('create_container', 'host_config', 'connect_container_to_network')):
try:
ret['create_container'] = \
_argspec(docker.APIClient.create_container).args
except AttributeError:
try:
ret['create_container'] = \
_argspec(docker.Client.create_container).args
except AttributeError:
raise CommandExecutionError(
'Coult not get create_container argspec'
)
try:
ret['host_config'] = \
_argspec(docker.types.HostConfig.__init__).args
except AttributeError:
try:
ret['host_config'] = \
_argspec(docker.utils.create_host_config).args
except AttributeError:
raise CommandExecutionError(
'Could not get create_host_config argspec'
)
try:
ret['connect_container_to_network'] = \
_argspec(docker.types.EndpointConfig.__init__).args
except AttributeError:
try:
ret['connect_container_to_network'] = \
_argspec(docker.utils.utils.create_endpoint_config).args
except AttributeError:
try:
ret['connect_container_to_network'] = \
_argspec(docker.utils.create_endpoint_config).args
except AttributeError:
raise CommandExecutionError(
'Could not get connect_container_to_network argspec'
)
for key, wrapped_func in (
('logs', docker.api.container.ContainerApiMixin.logs),
('create_network', docker.api.network.NetworkApiMixin.create_network)):
if not limit or key in limit:
try:
func_ref = wrapped_func
if six.PY2:
try:
# create_network is decorated, so we have to dig into the
# closure created by functools.wraps
ret[key] = \
_argspec(func_ref.__func__.__closure__[0].cell_contents).args
except (AttributeError, IndexError):
# functools.wraps changed (unlikely), bail out
ret[key] = []
else:
try:
# functools.wraps makes things a little easier in Python 3
ret[key] = _argspec(func_ref.__wrapped__).args
except AttributeError:
# functools.wraps changed (unlikely), bail out
ret[key] = []
except AttributeError:
# Function moved, bail out
ret[key] = []
if not limit or 'ipam_config' in limit:
try:
ret['ipam_config'] = _argspec(docker.types.IPAMPool.__init__).args
except AttributeError:
try:
ret['ipam_config'] = _argspec(docker.utils.create_ipam_pool).args
except AttributeError:
raise CommandExecutionError('Could not get ipam args')
for item in ret:
# The API version is passed automagically by the API code that imports
# these classes/functions and is not an arg that we will be passing, so
# remove it if present. Similarly, don't include "self" if it shows up
# in the arglist.
for argname in ('version', 'self'):
try:
ret[item].remove(argname)
except ValueError:
pass
# Remove any args in host or endpoint config from the create_container
# arglist. This keeps us from accidentally allowing args that docker-py has
# moved from the create_container function to the either the host or
# endpoint config.
for item in ('host_config', 'connect_container_to_network'):
for val in ret.get(item, []):
try:
ret['create_container'].remove(val)
except ValueError:
# Arg is not in create_container arglist
pass
for item in ('create_container', 'host_config', 'connect_container_to_network'):
if limit and item not in limit:
ret.pop(item, None)
try:
ret['logs'].remove('container')
except (KeyError, ValueError, TypeError):
pass
return ret
def create_ipam_config(*pools, **kwargs):
'''
Builds an IP address management (IPAM) config dictionary
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
try:
# docker-py 2.0 and newer
pool_args = salt.utils.args.get_function_argspec(
docker.types.IPAMPool.__init__).args
create_pool = docker.types.IPAMPool
create_config = docker.types.IPAMConfig
except AttributeError:
# docker-py < 2.0
pool_args = salt.utils.args.get_function_argspec(
docker.utils.create_ipam_pool).args
create_pool = docker.utils.create_ipam_pool
create_config = docker.utils.create_ipam_config
for primary_key, alias_key in (('driver', 'ipam_driver'),
('options', 'ipam_opts')):
if alias_key in kwargs:
alias_val = kwargs.pop(alias_key)
if primary_key in kwargs:
log.warning(
'docker.create_ipam_config: Both \'%s\' and \'%s\' '
'passed. Ignoring \'%s\'',
alias_key, primary_key, alias_key
)
else:
kwargs[primary_key] = alias_val
if salt.utils.data.is_dictlist(kwargs.get('options')):
kwargs['options'] = salt.utils.data.repack_dictlist(kwargs['options'])
# Get all of the IPAM pool args that were passed as individual kwargs
# instead of in the *pools tuple
pool_kwargs = {}
for key in list(kwargs):
if key in pool_args:
pool_kwargs[key] = kwargs.pop(key)
pool_configs = []
if pool_kwargs:
pool_configs.append(create_pool(**pool_kwargs))
pool_configs.extend([create_pool(**pool) for pool in pools])
if pool_configs:
# Sanity check the IPAM pools. docker-py's type/function for creating
# an IPAM pool will allow you to create a pool with a gateway, IP
# range, or map of aux addresses, even when no subnet is passed.
# However, attempting to use this IPAM pool when creating the network
# will cause the Docker Engine to throw an error.
if any('Subnet' not in pool for pool in pool_configs):
raise SaltInvocationError('A subnet is required in each IPAM pool')
else:
kwargs['pool_configs'] = pool_configs
ret = create_config(**kwargs)
pool_dicts = ret.get('Config')
if pool_dicts:
# When you inspect a network with custom IPAM configuration, only
# arguments which were explictly passed are reflected. By contrast,
# docker-py will include keys for arguments which were not passed in
# but set the value to None. Thus, for ease of comparison, the below
# loop will remove all keys with a value of None from the generated
# pool configs.
for idx, _ in enumerate(pool_dicts):
for key in list(pool_dicts[idx]):
if pool_dicts[idx][key] is None:
del pool_dicts[idx][key]
return ret
|
saltstack/salt
|
salt/utils/docker/__init__.py
|
create_ipam_config
|
python
|
def create_ipam_config(*pools, **kwargs):
'''
Builds an IP address management (IPAM) config dictionary
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
try:
# docker-py 2.0 and newer
pool_args = salt.utils.args.get_function_argspec(
docker.types.IPAMPool.__init__).args
create_pool = docker.types.IPAMPool
create_config = docker.types.IPAMConfig
except AttributeError:
# docker-py < 2.0
pool_args = salt.utils.args.get_function_argspec(
docker.utils.create_ipam_pool).args
create_pool = docker.utils.create_ipam_pool
create_config = docker.utils.create_ipam_config
for primary_key, alias_key in (('driver', 'ipam_driver'),
('options', 'ipam_opts')):
if alias_key in kwargs:
alias_val = kwargs.pop(alias_key)
if primary_key in kwargs:
log.warning(
'docker.create_ipam_config: Both \'%s\' and \'%s\' '
'passed. Ignoring \'%s\'',
alias_key, primary_key, alias_key
)
else:
kwargs[primary_key] = alias_val
if salt.utils.data.is_dictlist(kwargs.get('options')):
kwargs['options'] = salt.utils.data.repack_dictlist(kwargs['options'])
# Get all of the IPAM pool args that were passed as individual kwargs
# instead of in the *pools tuple
pool_kwargs = {}
for key in list(kwargs):
if key in pool_args:
pool_kwargs[key] = kwargs.pop(key)
pool_configs = []
if pool_kwargs:
pool_configs.append(create_pool(**pool_kwargs))
pool_configs.extend([create_pool(**pool) for pool in pools])
if pool_configs:
# Sanity check the IPAM pools. docker-py's type/function for creating
# an IPAM pool will allow you to create a pool with a gateway, IP
# range, or map of aux addresses, even when no subnet is passed.
# However, attempting to use this IPAM pool when creating the network
# will cause the Docker Engine to throw an error.
if any('Subnet' not in pool for pool in pool_configs):
raise SaltInvocationError('A subnet is required in each IPAM pool')
else:
kwargs['pool_configs'] = pool_configs
ret = create_config(**kwargs)
pool_dicts = ret.get('Config')
if pool_dicts:
# When you inspect a network with custom IPAM configuration, only
# arguments which were explictly passed are reflected. By contrast,
# docker-py will include keys for arguments which were not passed in
# but set the value to None. Thus, for ease of comparison, the below
# loop will remove all keys with a value of None from the generated
# pool configs.
for idx, _ in enumerate(pool_dicts):
for key in list(pool_dicts[idx]):
if pool_dicts[idx][key] is None:
del pool_dicts[idx][key]
return ret
|
Builds an IP address management (IPAM) config dictionary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/__init__.py#L276-L349
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def get_function_argspec(func, is_class_method=None):\n '''\n A small wrapper around getargspec that also supports callable classes\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n '''\n if not callable(func):\n raise TypeError('{0} is not a callable'.format(func))\n\n if six.PY2:\n if is_class_method is True:\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = inspect.getargspec(func)\n elif inspect.ismethod(func):\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = inspect.getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n else:\n if is_class_method is True:\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = _getargspec(func) # pylint: disable=redefined-variable-type\n elif inspect.ismethod(func):\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = _getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n return aspec\n",
"def is_dictlist(data):\n '''\n Returns True if data is a list of one-element dicts (as found in many SLS\n schemas), otherwise returns False\n '''\n if isinstance(data, list):\n for element in data:\n if isinstance(element, dict):\n if len(element) != 1:\n return False\n else:\n return False\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Common logic used by the docker state and execution module
This module contains logic to accommodate docker/salt CLI usage, as well as
input as formatted by states.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
# Import Salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.docker.translate
from salt.utils.docker.translate.helpers import split as _split
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.utils.args import get_function_argspec as _argspec
# Import 3rd-party libs
from salt.ext import six
try:
import docker
HAS_DOCKER_PY = True
except ImportError:
HAS_DOCKER_PY = False
# These next two imports are only necessary to have access to the needed
# functions so that we can get argspecs for the container config, host config,
# and networking config (see the get_client_args() function).
try:
import docker.types
except ImportError:
pass
try:
import docker.utils
except ImportError:
pass
NOTSET = object()
# Default timeout as of docker-py 1.0.0
CLIENT_TIMEOUT = 60
# Timeout for stopping the container, before a kill is invoked
SHUTDOWN_TIMEOUT = 10
log = logging.getLogger(__name__)
def get_client_args(limit=None):
if not HAS_DOCKER_PY:
raise CommandExecutionError('docker Python module not imported')
limit = salt.utils.args.split_input(limit or [])
ret = {}
if not limit or any(x in limit for x in
('create_container', 'host_config', 'connect_container_to_network')):
try:
ret['create_container'] = \
_argspec(docker.APIClient.create_container).args
except AttributeError:
try:
ret['create_container'] = \
_argspec(docker.Client.create_container).args
except AttributeError:
raise CommandExecutionError(
'Coult not get create_container argspec'
)
try:
ret['host_config'] = \
_argspec(docker.types.HostConfig.__init__).args
except AttributeError:
try:
ret['host_config'] = \
_argspec(docker.utils.create_host_config).args
except AttributeError:
raise CommandExecutionError(
'Could not get create_host_config argspec'
)
try:
ret['connect_container_to_network'] = \
_argspec(docker.types.EndpointConfig.__init__).args
except AttributeError:
try:
ret['connect_container_to_network'] = \
_argspec(docker.utils.utils.create_endpoint_config).args
except AttributeError:
try:
ret['connect_container_to_network'] = \
_argspec(docker.utils.create_endpoint_config).args
except AttributeError:
raise CommandExecutionError(
'Could not get connect_container_to_network argspec'
)
for key, wrapped_func in (
('logs', docker.api.container.ContainerApiMixin.logs),
('create_network', docker.api.network.NetworkApiMixin.create_network)):
if not limit or key in limit:
try:
func_ref = wrapped_func
if six.PY2:
try:
# create_network is decorated, so we have to dig into the
# closure created by functools.wraps
ret[key] = \
_argspec(func_ref.__func__.__closure__[0].cell_contents).args
except (AttributeError, IndexError):
# functools.wraps changed (unlikely), bail out
ret[key] = []
else:
try:
# functools.wraps makes things a little easier in Python 3
ret[key] = _argspec(func_ref.__wrapped__).args
except AttributeError:
# functools.wraps changed (unlikely), bail out
ret[key] = []
except AttributeError:
# Function moved, bail out
ret[key] = []
if not limit or 'ipam_config' in limit:
try:
ret['ipam_config'] = _argspec(docker.types.IPAMPool.__init__).args
except AttributeError:
try:
ret['ipam_config'] = _argspec(docker.utils.create_ipam_pool).args
except AttributeError:
raise CommandExecutionError('Could not get ipam args')
for item in ret:
# The API version is passed automagically by the API code that imports
# these classes/functions and is not an arg that we will be passing, so
# remove it if present. Similarly, don't include "self" if it shows up
# in the arglist.
for argname in ('version', 'self'):
try:
ret[item].remove(argname)
except ValueError:
pass
# Remove any args in host or endpoint config from the create_container
# arglist. This keeps us from accidentally allowing args that docker-py has
# moved from the create_container function to the either the host or
# endpoint config.
for item in ('host_config', 'connect_container_to_network'):
for val in ret.get(item, []):
try:
ret['create_container'].remove(val)
except ValueError:
# Arg is not in create_container arglist
pass
for item in ('create_container', 'host_config', 'connect_container_to_network'):
if limit and item not in limit:
ret.pop(item, None)
try:
ret['logs'].remove('container')
except (KeyError, ValueError, TypeError):
pass
return ret
def translate_input(translator,
skip_translate=None,
ignore_collisions=False,
validate_ip_addrs=True,
**kwargs):
'''
Translate CLI/SLS input into the format the API expects. The ``translator``
argument must be a module containing translation functions, within
salt.utils.docker.translate. A ``skip_translate`` kwarg can be passed to
control which arguments are translated. It can be either a comma-separated
list or an iterable containing strings (e.g. a list or tuple), and members
of that tuple will have their translation skipped. Optionally,
skip_translate can be set to True to skip *all* translation.
'''
kwargs = copy.deepcopy(salt.utils.args.clean_kwargs(**kwargs))
invalid = {}
collisions = []
if skip_translate is True:
# Skip all translation
return kwargs
else:
if not skip_translate:
skip_translate = ()
else:
try:
skip_translate = _split(skip_translate)
except AttributeError:
pass
if not hasattr(skip_translate, '__iter__'):
log.error('skip_translate is not an iterable, ignoring')
skip_translate = ()
try:
# Using list(kwargs) here because if there are any invalid arguments we
# will be popping them from the kwargs.
for key in list(kwargs):
real_key = translator.ALIASES.get(key, key)
if real_key in skip_translate:
continue
# ipam_pools is designed to be passed as a list of actual
# dictionaries, but if each of the dictionaries passed has a single
# element, it will be incorrectly repacked.
if key != 'ipam_pools' and salt.utils.data.is_dictlist(kwargs[key]):
kwargs[key] = salt.utils.data.repack_dictlist(kwargs[key])
try:
kwargs[key] = getattr(translator, real_key)(
kwargs[key],
validate_ip_addrs=validate_ip_addrs,
skip_translate=skip_translate)
except AttributeError:
log.debug('No translation function for argument \'%s\'', key)
continue
except SaltInvocationError as exc:
kwargs.pop(key)
invalid[key] = exc.strerror
try:
translator._merge_keys(kwargs)
except AttributeError:
pass
# Convert CLI versions of commands to their docker-py counterparts
for key in translator.ALIASES:
if key in kwargs:
new_key = translator.ALIASES[key]
value = kwargs.pop(key)
if new_key in kwargs:
collisions.append(new_key)
else:
kwargs[new_key] = value
try:
translator._post_processing(kwargs, skip_translate, invalid)
except AttributeError:
pass
except Exception as exc:
error_message = exc.__str__()
log.error(
'Error translating input: \'%s\'', error_message, exc_info=True)
else:
error_message = None
error_data = {}
if error_message is not None:
error_data['error_message'] = error_message
if invalid:
error_data['invalid'] = invalid
if collisions and not ignore_collisions:
for item in collisions:
error_data.setdefault('collisions', []).append(
'\'{0}\' is an alias for \'{1}\', they cannot both be used'
.format(translator.ALIASES_REVMAP[item], item)
)
if error_data:
raise CommandExecutionError(
'Failed to translate input', info=error_data)
return kwargs
|
saltstack/salt
|
salt/engines/logstash_engine.py
|
start
|
python
|
def start(host, port=5959, tag='salt/engine/logstash', proto='udp'):
'''
Listen to salt events and forward them to logstash
'''
if proto == 'tcp':
logstashHandler = logstash.TCPLogstashHandler
elif proto == 'udp':
logstashHandler = logstash.UDPLogstashHandler
logstash_logger = logging.getLogger('python-logstash-logger')
logstash_logger.setLevel(logging.INFO)
logstash_logger.addHandler(logstashHandler(host, port, version=1))
if __opts__.get('id').endswith('_master'):
event_bus = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir'],
listen=True)
else:
event_bus = salt.utils.event.get_event(
'minion',
transport=__opts__['transport'],
opts=__opts__,
sock_dir=__opts__['sock_dir'],
listen=True)
log.debug('Logstash engine started')
while True:
event = event_bus.get_event()
if event:
logstash_logger.info(tag, extra=event)
|
Listen to salt events and forward them to logstash
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/logstash_engine.py#L47-L78
|
[
"def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False):\n '''\n Return an event object suitable for the named transport\n '''\n # TODO: AIO core is separate from transport\n if opts['transport'] in ('zeromq', 'tcp', 'detect'):\n return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)\n",
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n"
] |
# -*- coding: utf-8 -*-
'''
An engine that reads messages from the salt event bus and pushes
them onto a logstash endpoint.
.. versionadded: 2015.8.0
:configuration:
Example configuration
.. code-block:: yaml
engines:
- logstash:
host: log.my_network.com
port: 5959
proto: tcp
:depends: logstash
'''
# Import python libraries
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.event
# Import third-party libs
try:
import logstash
except ImportError:
logstash = None
log = logging.getLogger(__name__)
__virtualname__ = 'logstash'
def __virtual__():
return __virtualname__ \
if logstash is not None \
else (False, 'python-logstash not installed')
|
saltstack/salt
|
salt/states/keystone_service.py
|
present
|
python
|
def present(name, auth=None, **kwargs):
'''
Ensure an service exists and is up-to-date
name
Name of the group
type
Service type
enabled
Boolean to control if service is enabled
description
An arbitrary description of the service
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
service = __salt__['keystoneng.service_get'](name=name)
if service is None:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Service will be created.'
return ret
kwargs['name'] = name
service = __salt__['keystoneng.service_create'](**kwargs)
ret['changes'] = service
ret['comment'] = 'Created service'
return ret
changes = __salt__['keystoneng.compare_changes'](service, **kwargs)
if changes:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Service will be updated.'
return ret
kwargs['name'] = service
__salt__['keystoneng.service_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated service'
return ret
|
Ensure an service exists and is up-to-date
name
Name of the group
type
Service type
enabled
Boolean to control if service is enabled
description
An arbitrary description of the service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_service.py#L43-L96
| null |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Keystone Services
=========================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions
Example States
.. code-block:: yaml
create service:
keystone_service.present:
- name: glance
- type: image
delete service:
keystone_service.absent:
- name: glance
create service with optional params:
keystone_service.present:
- name: glance
- type: image
- enabled: False
- description: 'OpenStack Image'
'''
from __future__ import absolute_import, unicode_literals, print_function
__virtualname__ = 'keystone_service'
def __virtual__():
if 'keystoneng.service_get' in __salt__:
return __virtualname__
return (False, 'The keystoneng execution module failed to load: shade python module is not available')
def absent(name, auth=None):
'''
Ensure service does not exist
name
Name of the service
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
service = __salt__['keystoneng.service_get'](name=name)
if service:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': service.id}
ret['comment'] = 'Service will be deleted.'
return ret
__salt__['keystoneng.service_delete'](name=service)
ret['changes']['id'] = service.id
ret['comment'] = 'Deleted service'
return ret
|
saltstack/salt
|
salt/states/keystone_service.py
|
absent
|
python
|
def absent(name, auth=None):
'''
Ensure service does not exist
name
Name of the service
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
service = __salt__['keystoneng.service_get'](name=name)
if service:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': service.id}
ret['comment'] = 'Service will be deleted.'
return ret
__salt__['keystoneng.service_delete'](name=service)
ret['changes']['id'] = service.id
ret['comment'] = 'Deleted service'
return ret
|
Ensure service does not exist
name
Name of the service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_service.py#L99-L127
| null |
# -*- coding: utf-8 -*-
'''
Management of OpenStack Keystone Services
=========================================
.. versionadded:: 2018.3.0
:depends: shade
:configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions
Example States
.. code-block:: yaml
create service:
keystone_service.present:
- name: glance
- type: image
delete service:
keystone_service.absent:
- name: glance
create service with optional params:
keystone_service.present:
- name: glance
- type: image
- enabled: False
- description: 'OpenStack Image'
'''
from __future__ import absolute_import, unicode_literals, print_function
__virtualname__ = 'keystone_service'
def __virtual__():
if 'keystoneng.service_get' in __salt__:
return __virtualname__
return (False, 'The keystoneng execution module failed to load: shade python module is not available')
def present(name, auth=None, **kwargs):
'''
Ensure an service exists and is up-to-date
name
Name of the group
type
Service type
enabled
Boolean to control if service is enabled
description
An arbitrary description of the service
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
service = __salt__['keystoneng.service_get'](name=name)
if service is None:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Service will be created.'
return ret
kwargs['name'] = name
service = __salt__['keystoneng.service_create'](**kwargs)
ret['changes'] = service
ret['comment'] = 'Created service'
return ret
changes = __salt__['keystoneng.compare_changes'](service, **kwargs)
if changes:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Service will be updated.'
return ret
kwargs['name'] = service
__salt__['keystoneng.service_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated service'
return ret
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
get_conn
|
python
|
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
|
Return a conn object for the passed VM data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L113-L136
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('subscription_id', 'certificate_path')\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
avail_locations
|
python
|
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
|
List available locations for Azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L153-L174
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
avail_images
|
python
|
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
|
List available images for Azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L177-L195
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
avail_sizes
|
python
|
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
|
Return a list of sizes from Azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L198-L213
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_nodes_full
|
python
|
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
|
List VMs on this Azure account, with full information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L234-L279
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def is_public_ip(ip):\n '''\n Determines whether an IP address falls within one of the private IP ranges\n '''\n if ':' in ip:\n # ipv6\n if ip.startswith('fe80:'):\n # ipv6 link local\n return False\n return True\n addr = ip_to_int(ip)\n if 167772160 < addr < 184549375:\n # 10.0.0.0/8\n return False\n elif 3232235520 < addr < 3232301055:\n # 192.168.0.0/16\n return False\n elif 2886729728 < addr < 2887778303:\n # 172.16.0.0/12\n return False\n elif 2130706432 < addr < 2147483647:\n # 127.0.0.0/8\n return False\n return True\n",
"def list_hosted_services(conn=None, call=None):\n '''\n List VMs on this Azure account, with full information\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_hosted_services function must be called with '\n '-f or --function'\n )\n\n if not conn:\n conn = get_conn()\n\n ret = {}\n services = conn.list_hosted_services()\n for service in services:\n props = service.hosted_service_properties\n ret[service.service_name] = {\n 'name': service.service_name,\n 'url': service.url,\n 'affinity_group': props.affinity_group,\n 'date_created': props.date_created,\n 'date_last_modified': props.date_last_modified,\n 'description': props.description,\n 'extended_properties': props.extended_properties,\n 'label': props.label,\n 'location': props.location,\n 'status': props.status,\n 'deployments': {},\n }\n deployments = conn.get_hosted_service_properties(\n service_name=service.service_name, embed_detail=True\n )\n for deployment in deployments.deployments:\n ret[service.service_name]['deployments'][deployment.name] = {\n 'configuration': deployment.configuration,\n 'created_time': deployment.created_time,\n 'deployment_slot': deployment.deployment_slot,\n 'extended_properties': deployment.extended_properties,\n 'input_endpoint_list': deployment.input_endpoint_list,\n 'label': deployment.label,\n 'last_modified_time': deployment.last_modified_time,\n 'locked': deployment.locked,\n 'name': deployment.name,\n 'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,\n 'private_id': deployment.private_id,\n 'role_instance_list': {},\n 'role_list': {},\n 'rollback_allowed': deployment.rollback_allowed,\n 'sdk_version': deployment.sdk_version,\n 'status': deployment.status,\n 'upgrade_domain_count': deployment.upgrade_domain_count,\n 'upgrade_status': deployment.upgrade_status,\n 'url': deployment.url,\n }\n for role_instance in deployment.role_instance_list:\n ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {\n 'fqdn': role_instance.fqdn,\n 'instance_error_code': role_instance.instance_error_code,\n 'instance_fault_domain': role_instance.instance_fault_domain,\n 'instance_name': role_instance.instance_name,\n 'instance_size': role_instance.instance_size,\n 'instance_state_details': role_instance.instance_state_details,\n 'instance_status': role_instance.instance_status,\n 'instance_upgrade_domain': role_instance.instance_upgrade_domain,\n 'ip_address': role_instance.ip_address,\n 'power_state': role_instance.power_state,\n 'role_name': role_instance.role_name,\n }\n for role in deployment.role_list:\n ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {\n 'role_name': role.role_name,\n 'os_version': role.os_version,\n }\n role_info = conn.get_role(\n service_name=service.service_name,\n deployment_name=deployment.name,\n role_name=role.role_name,\n )\n ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {\n 'availability_set_name': role_info.availability_set_name,\n 'configuration_sets': role_info.configuration_sets,\n 'data_virtual_hard_disks': role_info.data_virtual_hard_disks,\n 'os_version': role_info.os_version,\n 'role_name': role_info.role_name,\n 'role_size': role_info.role_size,\n 'role_type': role_info.role_type,\n }\n ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {\n 'disk_label': role_info.os_virtual_hard_disk.disk_label,\n 'disk_name': role_info.os_virtual_hard_disk.disk_name,\n 'host_caching': role_info.os_virtual_hard_disk.host_caching,\n 'media_link': role_info.os_virtual_hard_disk.media_link,\n 'os': role_info.os_virtual_hard_disk.os,\n 'source_image_name': role_info.os_virtual_hard_disk.source_image_name,\n }\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_hosted_services
|
python
|
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
|
List VMs on this Azure account, with full information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L282-L378
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_instance
|
python
|
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
|
Show the details from the provider concerning an instance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L393-L412
|
[
"def list_nodes_full(conn=None, call=None):\n '''\n List VMs on this Azure account, with full information\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_full function must be called with -f or --function.'\n )\n\n if not conn:\n conn = get_conn()\n\n ret = {}\n services = list_hosted_services(conn=conn, call=call)\n for service in services:\n for deployment in services[service]['deployments']:\n deploy_dict = services[service]['deployments'][deployment]\n deploy_dict_no_role_info = copy.deepcopy(deploy_dict)\n del deploy_dict_no_role_info['role_list']\n del deploy_dict_no_role_info['role_instance_list']\n roles = deploy_dict['role_list']\n for role in roles:\n role_instances = deploy_dict['role_instance_list']\n ret[role] = roles[role]\n ret[role].update(role_instances[role])\n ret[role]['id'] = role\n ret[role]['hosted_service'] = service\n if role_instances[role]['power_state'] == 'Started':\n ret[role]['state'] = 'running'\n elif role_instances[role]['power_state'] == 'Stopped':\n ret[role]['state'] = 'stopped'\n else:\n ret[role]['state'] = 'pending'\n ret[role]['private_ips'] = []\n ret[role]['public_ips'] = []\n ret[role]['deployment'] = deploy_dict_no_role_info\n ret[role]['url'] = deploy_dict['url']\n ip_address = role_instances[role]['ip_address']\n if ip_address:\n if salt.utils.cloud.is_public_ip(ip_address):\n ret[role]['public_ips'].append(ip_address)\n else:\n ret[role]['private_ips'].append(ip_address)\n ret[role]['size'] = role_instances[role]['instance_size']\n ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
create
|
python
|
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
|
Create a single VM from a data dict
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L415-L692
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def is_profile_configured(opts, provider, profile_name, vm_=None):\n '''\n Check if the requested profile contains the minimum required parameters for\n a profile.\n\n Required parameters include image and provider for all drivers, while some\n drivers also require size keys.\n\n .. versionadded:: 2015.8.0\n '''\n # Standard dict keys required by all drivers.\n required_keys = ['provider']\n alias, driver = provider.split(':')\n\n # Most drivers need an image to be specified, but some do not.\n non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']\n\n # Most drivers need a size, but some do not.\n non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',\n 'softlayer', 'softlayer_hw', 'vmware', 'vsphere',\n 'virtualbox', 'libvirt', 'oneandone', 'profitbricks']\n\n provider_key = opts['providers'][alias][driver]\n profile_key = opts['providers'][alias][driver]['profiles'][profile_name]\n\n # If cloning on Linode, size and image are not necessary.\n # They are obtained from the to-be-cloned VM.\n if driver == 'linode' and profile_key.get('clonefrom', False):\n non_image_drivers.append('linode')\n non_size_drivers.append('linode')\n elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):\n non_image_drivers.append('gce')\n\n # If cloning on VMware, specifying image is not necessary.\n if driver == 'vmware' and 'image' not in list(profile_key.keys()):\n non_image_drivers.append('vmware')\n\n if driver not in non_image_drivers:\n required_keys.append('image')\n if driver == 'vmware':\n required_keys.append('datastore')\n elif driver in ['linode', 'virtualbox']:\n required_keys.append('clonefrom')\n elif driver == 'nova':\n nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']\n if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):\n required_keys.extend(nova_image_keys)\n\n if driver not in non_size_drivers:\n required_keys.append('size')\n\n # Check if required fields are supplied in the provider config. If they\n # are present, remove it from the required_keys list.\n for item in list(required_keys):\n if item in provider_key:\n required_keys.remove(item)\n\n # If a vm_ dict was passed in, use that information to get any other configs\n # that we might have missed thus far, such as a option provided in a map file.\n if vm_:\n for item in list(required_keys):\n if item in vm_:\n required_keys.remove(item)\n\n # Check for remaining required parameters in the profile config.\n for item in required_keys:\n if profile_key.get(item, None) is None:\n # There's at least one required configuration item which is not set.\n log.error(\n \"The required '%s' configuration setting is missing from \"\n \"the '%s' profile, which is configured under the '%s' alias.\",\n item, profile_name, alias\n )\n return False\n\n return True\n",
"def show_instance(name, call=None):\n '''\n Show the details from the provider concerning an instance\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n\n nodes = list_nodes_full()\n # Find under which cloud service the name is listed, if any\n if name not in nodes:\n return {}\n if 'name' not in nodes[name]:\n nodes[name]['name'] = nodes[name]['id']\n try:\n __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)\n except TypeError:\n log.warning('Unable to show cache node data; this may be because the node has been deleted')\n return nodes[name]\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def wait_for_fun(fun, timeout=900, **kwargs):\n '''\n Wait until a function finishes, or times out\n '''\n start = time.time()\n log.debug('Attempting function %s', fun)\n trycount = 0\n while True:\n trycount += 1\n try:\n response = fun(**kwargs)\n if not isinstance(response, bool):\n return response\n except Exception as exc:\n log.debug('Caught exception in wait_for_fun: %s', exc)\n time.sleep(1)\n log.debug('Retrying function %s on (try %s)', fun, trycount)\n if time.time() - start > timeout:\n log.error('Function timed out: %s', timeout)\n return False\n",
"def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):\n '''\n Create and attach volumes to created node\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The create_attach_volumes action must be called with '\n '-a or --action.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n if isinstance(kwargs['volumes'], six.string_types):\n volumes = salt.utils.yaml.safe_load(kwargs['volumes'])\n else:\n volumes = kwargs['volumes']\n\n # From the Azure .NET SDK doc\n #\n # The Create Data Disk operation adds a data disk to a virtual\n # machine. There are three ways to create the data disk using the\n # Add Data Disk operation.\n # Option 1 - Attach an empty data disk to\n # the role by specifying the disk label and location of the disk\n # image. Do not include the DiskName and SourceMediaLink elements in\n # the request body. Include the MediaLink element and reference a\n # blob that is in the same geographical region as the role. You can\n # also omit the MediaLink element. In this usage, Azure will create\n # the data disk in the storage account configured as default for the\n # role.\n # Option 2 - Attach an existing data disk that is in the image\n # repository. Do not include the DiskName and SourceMediaLink\n # elements in the request body. Specify the data disk to use by\n # including the DiskName element. Note: If included the in the\n # response body, the MediaLink and LogicalDiskSizeInGB elements are\n # ignored.\n # Option 3 - Specify the location of a blob in your storage\n # account that contain a disk image to use. Include the\n # SourceMediaLink element. Note: If the MediaLink element\n # isincluded, it is ignored. (see\n # http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx\n # for more information)\n #\n # Here only option 1 is implemented\n conn = get_conn()\n ret = []\n for volume in volumes:\n if \"disk_name\" in volume:\n log.error(\"You cannot specify a disk_name. Only new volumes are allowed\")\n return False\n # Use the size keyword to set a size, but you can use the\n # azure name too. If neither is set, the disk has size 100GB\n volume.setdefault(\"logical_disk_size_in_gb\", volume.get(\"size\", 100))\n volume.setdefault(\"host_caching\", \"ReadOnly\")\n volume.setdefault(\"lun\", 0)\n # The media link is vm_name-disk-[0-15].vhd\n volume.setdefault(\"media_link\",\n kwargs[\"media_link\"][:-4] + \"-disk-{0}.vhd\".format(volume[\"lun\"]))\n volume.setdefault(\"disk_label\",\n kwargs[\"role_name\"] + \"-disk-{0}\".format(volume[\"lun\"]))\n volume_dict = {\n 'volume_name': volume[\"lun\"],\n 'disk_label': volume[\"disk_label\"]\n }\n\n # Preparing the volume dict to be passed with **\n kwargs_add_data_disk = [\"lun\", \"host_caching\", \"media_link\",\n \"disk_label\", \"disk_name\",\n \"logical_disk_size_in_gb\",\n \"source_media_link\"]\n for key in set(volume.keys()) - set(kwargs_add_data_disk):\n del volume[key]\n\n result = conn.add_data_disk(kwargs[\"service_name\"],\n kwargs[\"deployment_name\"],\n kwargs[\"role_name\"],\n **volume)\n _wait_for_async(conn, result.request_id)\n\n msg = (\n '{0} attached to {1} (aka {2})'.format(\n volume_dict['volume_name'],\n kwargs['role_name'],\n name)\n )\n log.info(msg)\n ret.append(msg)\n return ret\n",
"def _wait_for_async(conn, request_id):\n '''\n Helper function for azure tests\n '''\n count = 0\n log.debug('Waiting for asynchronous operation to complete')\n result = conn.get_operation_status(request_id)\n while result.status == 'InProgress':\n count = count + 1\n if count > 120:\n raise ValueError('Timed out waiting for asynchronous operation to complete.')\n time.sleep(5)\n result = conn.get_operation_status(request_id)\n\n if result.status != 'Succeeded':\n raise AzureException('Operation failed. {message} ({code})'\n .format(message=result.error.message,\n code=result.error.code))\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
create_attach_volumes
|
python
|
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
|
Create and attach volumes to created node
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L695-L786
|
[
"def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def _wait_for_async(conn, request_id):\n '''\n Helper function for azure tests\n '''\n count = 0\n log.debug('Waiting for asynchronous operation to complete')\n result = conn.get_operation_status(request_id)\n while result.status == 'InProgress':\n count = count + 1\n if count > 120:\n raise ValueError('Timed out waiting for asynchronous operation to complete.')\n time.sleep(5)\n result = conn.get_operation_status(request_id)\n\n if result.status != 'Succeeded':\n raise AzureException('Operation failed. {message} ({code})'\n .format(message=result.error.message,\n code=result.error.code))\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
_wait_for_async
|
python
|
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
|
Helper function for azure tests
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L881-L898
| null |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
destroy
|
python
|
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
|
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L901-L1016
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('subscription_id', 'certificate_path')\n )\n",
"def show_instance(name, call=None):\n '''\n Show the details from the provider concerning an instance\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n\n nodes = list_nodes_full()\n # Find under which cloud service the name is listed, if any\n if name not in nodes:\n return {}\n if 'name' not in nodes[name]:\n nodes[name]['name'] = nodes[name]['id']\n try:\n __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)\n except TypeError:\n log.warning('Unable to show cache node data; this may be because the node has been deleted')\n return nodes[name]\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def wait_for_fun(fun, timeout=900, **kwargs):\n '''\n Wait until a function finishes, or times out\n '''\n start = time.time()\n log.debug('Attempting function %s', fun)\n trycount = 0\n while True:\n trycount += 1\n try:\n response = fun(**kwargs)\n if not isinstance(response, bool):\n return response\n except Exception as exc:\n log.debug('Caught exception in wait_for_fun: %s', exc)\n time.sleep(1)\n log.debug('Retrying function %s on (try %s)', fun, trycount)\n if time.time() - start > timeout:\n log.error('Function timed out: %s', timeout)\n return False\n",
"def _wait_for_async(conn, request_id):\n '''\n Helper function for azure tests\n '''\n count = 0\n log.debug('Waiting for asynchronous operation to complete')\n result = conn.get_operation_status(request_id)\n while result.status == 'InProgress':\n count = count + 1\n if count > 120:\n raise ValueError('Timed out waiting for asynchronous operation to complete.')\n time.sleep(5)\n result = conn.get_operation_status(request_id)\n\n if result.status != 'Succeeded':\n raise AzureException('Operation failed. {message} ({code})'\n .format(message=result.error.message,\n code=result.error.code))\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_storage_services
|
python
|
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
|
List VMs on this Azure account, with full information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1019-L1043
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
get_operation_status
|
python
|
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
|
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1046-L1084
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_storage
|
python
|
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1087-L1112
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_storage
|
python
|
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
|
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1115-L1144
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_storage_keys
|
python
|
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
|
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1151-L1187
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n",
"def show_storage(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n List storage service properties\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f show_storage my-azure name=my_storage\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The show_storage function must be called with -f or --function.'\n )\n\n if not conn:\n conn = get_conn()\n\n if kwargs is None:\n kwargs = {}\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('A name must be specified as \"name\"')\n\n data = conn.get_storage_account_properties(\n kwargs['name'],\n )\n return object_to_dict(data)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
create_storage
|
python
|
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
|
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1194-L1243
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
update_storage
|
python
|
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
|
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1246-L1280
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def show_storage(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n List storage service properties\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f show_storage my-azure name=my_storage\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The show_storage function must be called with -f or --function.'\n )\n\n if not conn:\n conn = get_conn()\n\n if kwargs is None:\n kwargs = {}\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('A name must be specified as \"name\"')\n\n data = conn.get_storage_account_properties(\n kwargs['name'],\n )\n return object_to_dict(data)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
regenerate_storage_keys
|
python
|
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
|
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1283-L1320
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def show_storage_keys(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n Show storage account keys\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f show_storage_keys my-azure name=my_storage\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The show_storage_keys function must be called with -f or --function.'\n )\n\n if not conn:\n conn = get_conn()\n\n if kwargs is None:\n kwargs = {}\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('A name must be specified as \"name\"')\n\n try:\n data = conn.get_storage_account_keys(\n kwargs['name'],\n )\n except AzureMissingResourceHttpError as exc:\n storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')\n if storage_data['storage_service_properties']['status'] == 'Creating':\n raise SaltCloudSystemExit('The storage account keys have not yet been created.')\n else:\n raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))\n return object_to_dict(data)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
delete_storage
|
python
|
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
|
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1323-L1353
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_services
|
python
|
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
|
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1356-L1381
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_service
|
python
|
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
|
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1384-L1415
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
create_service
|
python
|
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
|
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1418-L1462
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
delete_service
|
python
|
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
|
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1465-L1495
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_disks
|
python
|
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1498-L1522
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_disk
|
python
|
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
|
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1525-L1552
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
cleanup_unattached_disks
|
python
|
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
|
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1559-L1594
|
[
"def delete_disk(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n Delete a specific disk associated with the account\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt-cloud -f delete_disk my-azure name=my_disk\n salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The delete_disk function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('A name must be specified as \"name\"')\n\n if not conn:\n conn = get_conn()\n\n try:\n data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))\n return {'Success': 'The disk was successfully deleted'}\n except AzureMissingResourceHttpError as exc:\n raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))\n",
"def list_disks(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n List disks associated with the account\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_disks my-azure\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The list_disks function must be called with -f or --function.'\n )\n\n if not conn:\n conn = get_conn()\n\n data = conn.list_disks()\n ret = {}\n for item in data.disks:\n ret[item.name] = object_to_dict(item)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
delete_disk
|
python
|
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
|
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1597-L1628
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
update_disk
|
python
|
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
|
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1631-L1667
|
[
"def show_disk(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return information about a disk\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f show_disk my-azure name=my_disk\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The get_disk function must be called with -f or --function.'\n )\n\n if not conn:\n conn = get_conn()\n\n if kwargs is None:\n kwargs = {}\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('A name must be specified as \"name\"')\n\n data = conn.get_disk(kwargs['name'])\n return object_to_dict(data)\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_service_certificates
|
python
|
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1670-L1700
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_service_certificate
|
python
|
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
|
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1703-L1741
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
add_service_certificate
|
python
|
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
|
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1748-L1794
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
delete_service_certificate
|
python
|
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
|
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1797-L1838
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_management_certificates
|
python
|
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1841-L1865
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_management_certificate
|
python
|
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
|
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1868-L1896
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
add_management_certificate
|
python
|
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
|
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1903-L1945
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_virtual_networks
|
python
|
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
|
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L1982-L2001
|
[
"def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):\n '''\n Perform a query directly against the Azure REST API\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n backend = config.get_cloud_config_value(\n 'backend',\n get_configured_provider(), __opts__, search_global=False\n )\n url = 'https://{management_host}/{subscription_id}/{path}'.format(\n management_host=management_host,\n subscription_id=subscription_id,\n path=path,\n )\n\n if header_dict is None:\n header_dict = {}\n\n header_dict['x-ms-version'] = '2014-06-01'\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=params,\n data=data,\n header_dict=header_dict,\n port=443,\n text=True,\n cert=certificate_path,\n backend=backend,\n decode=decode,\n decode_type='xml',\n )\n if 'dict' in result:\n return result['dict']\n return\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_input_endpoints
|
python
|
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
|
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2004-L2058
|
[
"def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):\n '''\n Perform a query directly against the Azure REST API\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n backend = config.get_cloud_config_value(\n 'backend',\n get_configured_provider(), __opts__, search_global=False\n )\n url = 'https://{management_host}/{subscription_id}/{path}'.format(\n management_host=management_host,\n subscription_id=subscription_id,\n path=path,\n )\n\n if header_dict is None:\n header_dict = {}\n\n header_dict['x-ms-version'] = '2014-06-01'\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=params,\n data=data,\n header_dict=header_dict,\n port=443,\n text=True,\n cert=certificate_path,\n backend=backend,\n decode=decode,\n decode_type='xml',\n )\n if 'dict' in result:\n return result['dict']\n return\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_input_endpoint
|
python
|
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
|
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2061-L2086
|
[
"def list_input_endpoints(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n List input endpoints associated with the deployment\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The list_input_endpoints function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n if 'service' not in kwargs:\n raise SaltCloudSystemExit('A service name must be specified as \"service\"')\n\n if 'deployment' not in kwargs:\n raise SaltCloudSystemExit('A deployment name must be specified as \"deployment\"')\n\n path = 'services/hostedservices/{0}/deployments/{1}'.format(\n kwargs['service'],\n kwargs['deployment'],\n )\n\n data = query(path)\n if data is None:\n raise SaltCloudSystemExit(\n 'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(\n kwargs['service'],\n kwargs['deployment']\n )\n )\n\n ret = {}\n for item in data:\n if 'Role' in item:\n role = item['Role']\n if not isinstance(role, dict):\n return ret\n input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')\n if not input_endpoint:\n continue\n if not isinstance(input_endpoint, list):\n input_endpoint = [input_endpoint]\n for endpoint in input_endpoint:\n ret[endpoint['Name']] = endpoint\n return ret\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
update_input_endpoint
|
python
|
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
|
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2093-L2204
|
[
"def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):\n '''\n Perform a query directly against the Azure REST API\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n backend = config.get_cloud_config_value(\n 'backend',\n get_configured_provider(), __opts__, search_global=False\n )\n url = 'https://{management_host}/{subscription_id}/{path}'.format(\n management_host=management_host,\n subscription_id=subscription_id,\n path=path,\n )\n\n if header_dict is None:\n header_dict = {}\n\n header_dict['x-ms-version'] = '2014-06-01'\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=params,\n data=data,\n header_dict=header_dict,\n port=443,\n text=True,\n cert=certificate_path,\n backend=backend,\n decode=decode,\n decode_type='xml',\n )\n if 'dict' in result:\n return result['dict']\n return\n",
"def list_input_endpoints(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n List input endpoints associated with the deployment\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The list_input_endpoints function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n if 'service' not in kwargs:\n raise SaltCloudSystemExit('A service name must be specified as \"service\"')\n\n if 'deployment' not in kwargs:\n raise SaltCloudSystemExit('A deployment name must be specified as \"deployment\"')\n\n path = 'services/hostedservices/{0}/deployments/{1}'.format(\n kwargs['service'],\n kwargs['deployment'],\n )\n\n data = query(path)\n if data is None:\n raise SaltCloudSystemExit(\n 'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(\n kwargs['service'],\n kwargs['deployment']\n )\n )\n\n ret = {}\n for item in data:\n if 'Role' in item:\n role = item['Role']\n if not isinstance(role, dict):\n return ret\n input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')\n if not input_endpoint:\n continue\n if not isinstance(input_endpoint, list):\n input_endpoint = [input_endpoint]\n for endpoint in input_endpoint:\n ret[endpoint['Name']] = endpoint\n return ret\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
add_input_endpoint
|
python
|
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
|
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2207-L2228
|
[
"def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):\n '''\n .. versionadded:: 2015.8.0\n\n Update an input endpoint associated with the deployment. Please note that\n there may be a delay before the changes show up.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f update_input_endpoint my-azure service=myservice \\\\\n deployment=mydeployment role=myrole name=HTTP local_port=80 \\\\\n port=80 protocol=tcp enable_direct_server_return=False \\\\\n timeout_for_tcp_idle_connection=4\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The update_input_endpoint function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n if 'service' not in kwargs:\n raise SaltCloudSystemExit('A service name must be specified as \"service\"')\n\n if 'deployment' not in kwargs:\n raise SaltCloudSystemExit('A deployment name must be specified as \"deployment\"')\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('An endpoint name must be specified as \"name\"')\n\n if 'role' not in kwargs:\n raise SaltCloudSystemExit('An role name must be specified as \"role\"')\n\n if activity != 'delete':\n if 'port' not in kwargs:\n raise SaltCloudSystemExit('An endpoint port must be specified as \"port\"')\n\n if 'protocol' not in kwargs:\n raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as \"protocol\"')\n\n if 'local_port' not in kwargs:\n kwargs['local_port'] = kwargs['port']\n\n if 'enable_direct_server_return' not in kwargs:\n kwargs['enable_direct_server_return'] = False\n kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()\n\n if 'timeout_for_tcp_idle_connection' not in kwargs:\n kwargs['timeout_for_tcp_idle_connection'] = 4\n\n old_endpoints = list_input_endpoints(kwargs, call='function')\n\n endpoints_xml = ''\n endpoint_xml = '''\n <InputEndpoint>\n <LocalPort>{local_port}</LocalPort>\n <Name>{name}</Name>\n <Port>{port}</Port>\n <Protocol>{protocol}</Protocol>\n <EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>\n <IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>\n </InputEndpoint>'''\n\n if activity == 'add':\n old_endpoints[kwargs['name']] = kwargs\n old_endpoints[kwargs['name']]['Name'] = kwargs['name']\n\n for endpoint in old_endpoints:\n if old_endpoints[endpoint]['Name'] == kwargs['name']:\n if activity != 'delete':\n this_endpoint_xml = endpoint_xml.format(**kwargs)\n endpoints_xml += this_endpoint_xml\n else:\n this_endpoint_xml = endpoint_xml.format(\n local_port=old_endpoints[endpoint]['LocalPort'],\n name=old_endpoints[endpoint]['Name'],\n port=old_endpoints[endpoint]['Port'],\n protocol=old_endpoints[endpoint]['Protocol'],\n enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],\n timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),\n )\n endpoints_xml += this_endpoint_xml\n\n request_xml = '''<PersistentVMRole xmlns=\"http://schemas.microsoft.com/windowsazure\"\nxmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n <ConfigurationSets>\n <ConfigurationSet>\n <ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>\n <InputEndpoints>{0}\n </InputEndpoints>\n </ConfigurationSet>\n </ConfigurationSets>\n <OSVirtualHardDisk>\n </OSVirtualHardDisk>\n</PersistentVMRole>'''.format(endpoints_xml)\n\n path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(\n kwargs['service'],\n kwargs['deployment'],\n kwargs['role'],\n )\n query(\n path=path,\n method='PUT',\n header_dict={'Content-Type': 'application/xml'},\n data=request_xml,\n decode=False,\n )\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
delete_input_endpoint
|
python
|
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
|
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2231-L2250
|
[
"def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):\n '''\n .. versionadded:: 2015.8.0\n\n Update an input endpoint associated with the deployment. Please note that\n there may be a delay before the changes show up.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f update_input_endpoint my-azure service=myservice \\\\\n deployment=mydeployment role=myrole name=HTTP local_port=80 \\\\\n port=80 protocol=tcp enable_direct_server_return=False \\\\\n timeout_for_tcp_idle_connection=4\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The update_input_endpoint function must be called with -f or --function.'\n )\n\n if kwargs is None:\n kwargs = {}\n\n if 'service' not in kwargs:\n raise SaltCloudSystemExit('A service name must be specified as \"service\"')\n\n if 'deployment' not in kwargs:\n raise SaltCloudSystemExit('A deployment name must be specified as \"deployment\"')\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('An endpoint name must be specified as \"name\"')\n\n if 'role' not in kwargs:\n raise SaltCloudSystemExit('An role name must be specified as \"role\"')\n\n if activity != 'delete':\n if 'port' not in kwargs:\n raise SaltCloudSystemExit('An endpoint port must be specified as \"port\"')\n\n if 'protocol' not in kwargs:\n raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as \"protocol\"')\n\n if 'local_port' not in kwargs:\n kwargs['local_port'] = kwargs['port']\n\n if 'enable_direct_server_return' not in kwargs:\n kwargs['enable_direct_server_return'] = False\n kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()\n\n if 'timeout_for_tcp_idle_connection' not in kwargs:\n kwargs['timeout_for_tcp_idle_connection'] = 4\n\n old_endpoints = list_input_endpoints(kwargs, call='function')\n\n endpoints_xml = ''\n endpoint_xml = '''\n <InputEndpoint>\n <LocalPort>{local_port}</LocalPort>\n <Name>{name}</Name>\n <Port>{port}</Port>\n <Protocol>{protocol}</Protocol>\n <EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>\n <IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>\n </InputEndpoint>'''\n\n if activity == 'add':\n old_endpoints[kwargs['name']] = kwargs\n old_endpoints[kwargs['name']]['Name'] = kwargs['name']\n\n for endpoint in old_endpoints:\n if old_endpoints[endpoint]['Name'] == kwargs['name']:\n if activity != 'delete':\n this_endpoint_xml = endpoint_xml.format(**kwargs)\n endpoints_xml += this_endpoint_xml\n else:\n this_endpoint_xml = endpoint_xml.format(\n local_port=old_endpoints[endpoint]['LocalPort'],\n name=old_endpoints[endpoint]['Name'],\n port=old_endpoints[endpoint]['Port'],\n protocol=old_endpoints[endpoint]['Protocol'],\n enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],\n timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),\n )\n endpoints_xml += this_endpoint_xml\n\n request_xml = '''<PersistentVMRole xmlns=\"http://schemas.microsoft.com/windowsazure\"\nxmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n <ConfigurationSets>\n <ConfigurationSet>\n <ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>\n <InputEndpoints>{0}\n </InputEndpoints>\n </ConfigurationSet>\n </ConfigurationSets>\n <OSVirtualHardDisk>\n </OSVirtualHardDisk>\n</PersistentVMRole>'''.format(endpoints_xml)\n\n path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(\n kwargs['service'],\n kwargs['deployment'],\n kwargs['role'],\n )\n query(\n path=path,\n method='PUT',\n header_dict={'Content-Type': 'application/xml'},\n data=request_xml,\n decode=False,\n )\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_deployment
|
python
|
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
|
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2253-L2286
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_affinity_groups
|
python
|
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2293-L2317
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_affinity_group
|
python
|
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
|
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2320-L2348
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
create_affinity_group
|
python
|
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
|
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2355-L2396
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
update_affinity_group
|
python
|
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
|
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2399-L2433
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n",
"def show_affinity_group(kwargs=None, conn=None, call=None):\n '''\n .. versionadded:: 2015.8.0\n\n Show an affinity group associated with the account\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f show_affinity_group my-azure service=myservice \\\\\n deployment=mydeployment name=SSH\n '''\n if call != 'function':\n raise SaltCloudSystemExit(\n 'The show_affinity_group function must be called with -f or --function.'\n )\n\n if not conn:\n conn = get_conn()\n\n if kwargs is None:\n kwargs = {}\n\n if 'name' not in kwargs:\n raise SaltCloudSystemExit('An affinity group name must be specified as \"name\"')\n\n data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])\n return object_to_dict(data)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
delete_affinity_group
|
python
|
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
|
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2436-L2466
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n certificate_path = config.get_cloud_config_value(\n 'certificate_path',\n get_configured_provider(), __opts__, search_global=False\n )\n subscription_id = salt.utils.stringutils.to_str(\n config.get_cloud_config_value(\n 'subscription_id',\n get_configured_provider(), __opts__, search_global=False\n )\n )\n management_host = config.get_cloud_config_value(\n 'management_host',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='management.core.windows.net'\n )\n return azure.servicemanagement.ServiceManagementService(\n subscription_id, certificate_path, management_host\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
get_storage_conn
|
python
|
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
|
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2469-L2490
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('subscription_id', 'certificate_path')\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
make_blob_url
|
python
|
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2493-L2546
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_storage_containers
|
python
|
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2549-L2573
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
create_storage_container
|
python
|
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
|
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2576-L2615
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azure',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(data)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.