repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/states/keystone.py
_api_version
def _api_version(profile=None, **connection_args): ''' Sets global variables _OS_IDENTITY_API_VERSION and _TENANT_ID depending on API version. ''' global _TENANT_ID global _OS_IDENTITY_API_VERSION try: if float(__salt__['keystone.api_version'](profile=profile, **connection_args).strip('v')) >= 3: _TENANT_ID = 'project_id' _OS_IDENTITY_API_VERSION = 3 except KeyError: pass
python
def _api_version(profile=None, **connection_args): ''' Sets global variables _OS_IDENTITY_API_VERSION and _TENANT_ID depending on API version. ''' global _TENANT_ID global _OS_IDENTITY_API_VERSION try: if float(__salt__['keystone.api_version'](profile=profile, **connection_args).strip('v')) >= 3: _TENANT_ID = 'project_id' _OS_IDENTITY_API_VERSION = 3 except KeyError: pass
[ "def", "_api_version", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "global", "_TENANT_ID", "global", "_OS_IDENTITY_API_VERSION", "try", ":", "if", "float", "(", "__salt__", "[", "'keystone.api_version'", "]", "(", "profile", "=", "...
Sets global variables _OS_IDENTITY_API_VERSION and _TENANT_ID depending on API version.
[ "Sets", "global", "variables", "_OS_IDENTITY_API_VERSION", "and", "_TENANT_ID", "depending", "on", "API", "version", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L83-L95
train
saltstack/salt
salt/states/keystone.py
user_present
def user_present(name, password, email, tenant=None, enabled=True, roles=None, profile=None, password_reset=True, project=None, **connection_args): ''' Ensure that the keystone user is present with the specified properties. name The name of the user to manage password The password to use for this user. .. note:: If the user already exists and a different password was set for the user than the one specified here, the password for the user will be updated. Please set the ``password_reset`` option to ``False`` if this is not the desired behavior. password_reset Whether or not to reset password after initial set. Defaults to ``True``. email The email address for this user tenant The tenant (name) for this user project The project (name) for this user (overrides tenant in api v3) enabled Availability state for this user roles The roles the user should have under given tenants. Passed as a dictionary mapping tenant names to a list of roles in this tenant, i.e.:: roles: admin: # tenant - admin # role service: - admin - Member ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User "{0}" will be updated'.format(name)} _api_version(profile=profile, **connection_args) if project and not tenant: tenant = project # Validate tenant if set if tenant is not None: tenantdata = __salt__['keystone.tenant_get'](name=tenant, profile=profile, **connection_args) if 'Error' in tenantdata: ret['result'] = False ret['comment'] = 'Tenant / project "{0}" does not exist'.format(tenant) return ret tenant_id = tenantdata[tenant]['id'] else: tenant_id = None # Check if user is already present user = __salt__['keystone.user_get'](name=name, profile=profile, **connection_args) if 'Error' not in user: change_email = False change_enabled = False change_tenant = False change_password = False if user[name].get('email', None) != email: change_email = True if user[name].get('enabled', None) != enabled: change_enabled = True if tenant and (_TENANT_ID not in user[name] or user[name].get(_TENANT_ID, None) != tenant_id): change_tenant = True if (password_reset is True and not __salt__['keystone.user_verify_password'](name=name, password=password, profile=profile, **connection_args)): change_password = True if __opts__.get('test') and (change_email or change_enabled or change_tenant or change_password): ret['result'] = None ret['comment'] = 'User "{0}" will be updated'.format(name) if change_email is True: ret['changes']['Email'] = 'Will be updated' if change_enabled is True: ret['changes']['Enabled'] = 'Will be True' if change_tenant is True: ret['changes']['Tenant'] = 'Will be added to "{0}" tenant'.format(tenant) if change_password is True: ret['changes']['Password'] = 'Will be updated' return ret ret['comment'] = 'User "{0}" is already present'.format(name) if change_email: __salt__['keystone.user_update'](name=name, email=email, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Email'] = 'Updated' if change_enabled: __salt__['keystone.user_update'](name=name, enabled=enabled, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Enabled'] = 'Now {0}'.format(enabled) if change_tenant: __salt__['keystone.user_update'](name=name, tenant=tenant, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Tenant'] = 'Added to "{0}" tenant'.format(tenant) if change_password: __salt__['keystone.user_password_update'](name=name, password=password, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Password'] = 'Updated' if roles: for tenant in roles: args = dict({'user_name': name, 'tenant_name': tenant, 'profile': profile}, **connection_args) tenant_roles = __salt__['keystone.user_role_list'](**args) for role in roles[tenant]: if role not in tenant_roles: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'User roles "{0}" will been updated'.format(name) return ret addargs = dict({'user': name, 'role': role, 'tenant': tenant, 'profile': profile}, **connection_args) newrole = __salt__['keystone.user_role_add'](**addargs) if 'roles' in ret['changes']: ret['changes']['roles'].append(newrole) else: ret['changes']['roles'] = [newrole] roles_to_remove = list(set(tenant_roles) - set(roles[tenant])) for role in roles_to_remove: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'User roles "{0}" will been updated'.format(name) return ret addargs = dict({'user': name, 'role': role, 'tenant': tenant, 'profile': profile}, **connection_args) oldrole = __salt__['keystone.user_role_remove'](**addargs) if 'roles' in ret['changes']: ret['changes']['roles'].append(oldrole) else: ret['changes']['roles'] = [oldrole] else: # Create that user! if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Keystone user "{0}" will be added'.format(name) ret['changes']['User'] = 'Will be created' return ret __salt__['keystone.user_create'](name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled, profile=profile, **connection_args) if roles: for tenant in roles: for role in roles[tenant]: __salt__['keystone.user_role_add'](user=name, role=role, tenant=tenant, profile=profile, **connection_args) ret['comment'] = 'Keystone user {0} has been added'.format(name) ret['changes']['User'] = 'Created' return ret
python
def user_present(name, password, email, tenant=None, enabled=True, roles=None, profile=None, password_reset=True, project=None, **connection_args): ''' Ensure that the keystone user is present with the specified properties. name The name of the user to manage password The password to use for this user. .. note:: If the user already exists and a different password was set for the user than the one specified here, the password for the user will be updated. Please set the ``password_reset`` option to ``False`` if this is not the desired behavior. password_reset Whether or not to reset password after initial set. Defaults to ``True``. email The email address for this user tenant The tenant (name) for this user project The project (name) for this user (overrides tenant in api v3) enabled Availability state for this user roles The roles the user should have under given tenants. Passed as a dictionary mapping tenant names to a list of roles in this tenant, i.e.:: roles: admin: # tenant - admin # role service: - admin - Member ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User "{0}" will be updated'.format(name)} _api_version(profile=profile, **connection_args) if project and not tenant: tenant = project # Validate tenant if set if tenant is not None: tenantdata = __salt__['keystone.tenant_get'](name=tenant, profile=profile, **connection_args) if 'Error' in tenantdata: ret['result'] = False ret['comment'] = 'Tenant / project "{0}" does not exist'.format(tenant) return ret tenant_id = tenantdata[tenant]['id'] else: tenant_id = None # Check if user is already present user = __salt__['keystone.user_get'](name=name, profile=profile, **connection_args) if 'Error' not in user: change_email = False change_enabled = False change_tenant = False change_password = False if user[name].get('email', None) != email: change_email = True if user[name].get('enabled', None) != enabled: change_enabled = True if tenant and (_TENANT_ID not in user[name] or user[name].get(_TENANT_ID, None) != tenant_id): change_tenant = True if (password_reset is True and not __salt__['keystone.user_verify_password'](name=name, password=password, profile=profile, **connection_args)): change_password = True if __opts__.get('test') and (change_email or change_enabled or change_tenant or change_password): ret['result'] = None ret['comment'] = 'User "{0}" will be updated'.format(name) if change_email is True: ret['changes']['Email'] = 'Will be updated' if change_enabled is True: ret['changes']['Enabled'] = 'Will be True' if change_tenant is True: ret['changes']['Tenant'] = 'Will be added to "{0}" tenant'.format(tenant) if change_password is True: ret['changes']['Password'] = 'Will be updated' return ret ret['comment'] = 'User "{0}" is already present'.format(name) if change_email: __salt__['keystone.user_update'](name=name, email=email, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Email'] = 'Updated' if change_enabled: __salt__['keystone.user_update'](name=name, enabled=enabled, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Enabled'] = 'Now {0}'.format(enabled) if change_tenant: __salt__['keystone.user_update'](name=name, tenant=tenant, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Tenant'] = 'Added to "{0}" tenant'.format(tenant) if change_password: __salt__['keystone.user_password_update'](name=name, password=password, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been updated'.format(name) ret['changes']['Password'] = 'Updated' if roles: for tenant in roles: args = dict({'user_name': name, 'tenant_name': tenant, 'profile': profile}, **connection_args) tenant_roles = __salt__['keystone.user_role_list'](**args) for role in roles[tenant]: if role not in tenant_roles: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'User roles "{0}" will been updated'.format(name) return ret addargs = dict({'user': name, 'role': role, 'tenant': tenant, 'profile': profile}, **connection_args) newrole = __salt__['keystone.user_role_add'](**addargs) if 'roles' in ret['changes']: ret['changes']['roles'].append(newrole) else: ret['changes']['roles'] = [newrole] roles_to_remove = list(set(tenant_roles) - set(roles[tenant])) for role in roles_to_remove: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'User roles "{0}" will been updated'.format(name) return ret addargs = dict({'user': name, 'role': role, 'tenant': tenant, 'profile': profile}, **connection_args) oldrole = __salt__['keystone.user_role_remove'](**addargs) if 'roles' in ret['changes']: ret['changes']['roles'].append(oldrole) else: ret['changes']['roles'] = [oldrole] else: # Create that user! if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Keystone user "{0}" will be added'.format(name) ret['changes']['User'] = 'Will be created' return ret __salt__['keystone.user_create'](name=name, password=password, email=email, tenant_id=tenant_id, enabled=enabled, profile=profile, **connection_args) if roles: for tenant in roles: for role in roles[tenant]: __salt__['keystone.user_role_add'](user=name, role=role, tenant=tenant, profile=profile, **connection_args) ret['comment'] = 'Keystone user {0} has been added'.format(name) ret['changes']['User'] = 'Created' return ret
[ "def", "user_present", "(", "name", ",", "password", ",", "email", ",", "tenant", "=", "None", ",", "enabled", "=", "True", ",", "roles", "=", "None", ",", "profile", "=", "None", ",", "password_reset", "=", "True", ",", "project", "=", "None", ",", ...
Ensure that the keystone user is present with the specified properties. name The name of the user to manage password The password to use for this user. .. note:: If the user already exists and a different password was set for the user than the one specified here, the password for the user will be updated. Please set the ``password_reset`` option to ``False`` if this is not the desired behavior. password_reset Whether or not to reset password after initial set. Defaults to ``True``. email The email address for this user tenant The tenant (name) for this user project The project (name) for this user (overrides tenant in api v3) enabled Availability state for this user roles The roles the user should have under given tenants. Passed as a dictionary mapping tenant names to a list of roles in this tenant, i.e.:: roles: admin: # tenant - admin # role service: - admin - Member
[ "Ensure", "that", "the", "keystone", "user", "is", "present", "with", "the", "specified", "properties", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L98-L298
train
saltstack/salt
salt/states/keystone.py
user_absent
def user_absent(name, profile=None, **connection_args): ''' Ensure that the keystone user is absent. name The name of the user that should not exist ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User "{0}" is already absent'.format(name)} # Check if user is present user = __salt__['keystone.user_get'](name=name, profile=profile, **connection_args) if 'Error' not in user: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'User "{0}" will be deleted'.format(name) return ret # Delete that user! __salt__['keystone.user_delete'](name=name, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been deleted'.format(name) ret['changes']['User'] = 'Deleted' return ret
python
def user_absent(name, profile=None, **connection_args): ''' Ensure that the keystone user is absent. name The name of the user that should not exist ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User "{0}" is already absent'.format(name)} # Check if user is present user = __salt__['keystone.user_get'](name=name, profile=profile, **connection_args) if 'Error' not in user: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'User "{0}" will be deleted'.format(name) return ret # Delete that user! __salt__['keystone.user_delete'](name=name, profile=profile, **connection_args) ret['comment'] = 'User "{0}" has been deleted'.format(name) ret['changes']['User'] = 'Deleted' return ret
[ "def", "user_absent", "(", "name", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'User \"{0}\" is ...
Ensure that the keystone user is absent. name The name of the user that should not exist
[ "Ensure", "that", "the", "keystone", "user", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L301-L327
train
saltstack/salt
salt/states/keystone.py
tenant_present
def tenant_present(name, description=None, enabled=True, profile=None, **connection_args): ''' Ensures that the keystone tenant exists name The name of the tenant to manage description The description to use for this tenant enabled Availability state for this tenant ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Tenant / project "{0}" already exists'.format(name)} _api_version(profile=profile, **connection_args) # Check if tenant is already present tenant = __salt__['keystone.tenant_get'](name=name, profile=profile, **connection_args) if 'Error' not in tenant: if tenant[name].get('description', None) != description: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be updated'.format(name) ret['changes']['Description'] = 'Will be updated' return ret __salt__['keystone.tenant_update'](name=name, description=description, enabled=enabled, profile=profile, **connection_args) ret['comment'] = 'Tenant / project "{0}" has been updated'.format(name) ret['changes']['Description'] = 'Updated' if tenant[name].get('enabled', None) != enabled: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be updated'.format(name) ret['changes']['Enabled'] = 'Will be {0}'.format(enabled) return ret __salt__['keystone.tenant_update'](name=name, description=description, enabled=enabled, profile=profile, **connection_args) ret['comment'] = 'Tenant / project "{0}" has been updated'.format(name) ret['changes']['Enabled'] = 'Now {0}'.format(enabled) else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be added'.format(name) ret['changes']['Tenant'] = 'Will be created' return ret # Create tenant if _OS_IDENTITY_API_VERSION > 2: created = __salt__['keystone.project_create'](name=name, domain='default', description=description, enabled=enabled, profile=profile, **connection_args) else: created = __salt__['keystone.tenant_create'](name=name, description=description, enabled=enabled, profile=profile, **connection_args) ret['changes']['Tenant'] = 'Created' if created is True else 'Failed' ret['result'] = created ret['comment'] = 'Tenant / project "{0}" has been added'.format(name) return ret
python
def tenant_present(name, description=None, enabled=True, profile=None, **connection_args): ''' Ensures that the keystone tenant exists name The name of the tenant to manage description The description to use for this tenant enabled Availability state for this tenant ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Tenant / project "{0}" already exists'.format(name)} _api_version(profile=profile, **connection_args) # Check if tenant is already present tenant = __salt__['keystone.tenant_get'](name=name, profile=profile, **connection_args) if 'Error' not in tenant: if tenant[name].get('description', None) != description: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be updated'.format(name) ret['changes']['Description'] = 'Will be updated' return ret __salt__['keystone.tenant_update'](name=name, description=description, enabled=enabled, profile=profile, **connection_args) ret['comment'] = 'Tenant / project "{0}" has been updated'.format(name) ret['changes']['Description'] = 'Updated' if tenant[name].get('enabled', None) != enabled: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be updated'.format(name) ret['changes']['Enabled'] = 'Will be {0}'.format(enabled) return ret __salt__['keystone.tenant_update'](name=name, description=description, enabled=enabled, profile=profile, **connection_args) ret['comment'] = 'Tenant / project "{0}" has been updated'.format(name) ret['changes']['Enabled'] = 'Now {0}'.format(enabled) else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be added'.format(name) ret['changes']['Tenant'] = 'Will be created' return ret # Create tenant if _OS_IDENTITY_API_VERSION > 2: created = __salt__['keystone.project_create'](name=name, domain='default', description=description, enabled=enabled, profile=profile, **connection_args) else: created = __salt__['keystone.tenant_create'](name=name, description=description, enabled=enabled, profile=profile, **connection_args) ret['changes']['Tenant'] = 'Created' if created is True else 'Failed' ret['result'] = created ret['comment'] = 'Tenant / project "{0}" has been added'.format(name) return ret
[ "def", "tenant_present", "(", "name", ",", "description", "=", "None", ",", "enabled", "=", "True", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",",...
Ensures that the keystone tenant exists name The name of the tenant to manage description The description to use for this tenant enabled Availability state for this tenant
[ "Ensures", "that", "the", "keystone", "tenant", "exists" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L330-L399
train
saltstack/salt
salt/states/keystone.py
tenant_absent
def tenant_absent(name, profile=None, **connection_args): ''' Ensure that the keystone tenant is absent. name The name of the tenant that should not exist ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Tenant / project "{0}" is already absent'.format(name)} # Check if tenant is present tenant = __salt__['keystone.tenant_get'](name=name, profile=profile, **connection_args) if 'Error' not in tenant: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be deleted'.format(name) return ret # Delete tenant __salt__['keystone.tenant_delete'](name=name, profile=profile, **connection_args) ret['comment'] = 'Tenant / project "{0}" has been deleted'.format(name) ret['changes']['Tenant/Project'] = 'Deleted' return ret
python
def tenant_absent(name, profile=None, **connection_args): ''' Ensure that the keystone tenant is absent. name The name of the tenant that should not exist ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Tenant / project "{0}" is already absent'.format(name)} # Check if tenant is present tenant = __salt__['keystone.tenant_get'](name=name, profile=profile, **connection_args) if 'Error' not in tenant: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Tenant / project "{0}" will be deleted'.format(name) return ret # Delete tenant __salt__['keystone.tenant_delete'](name=name, profile=profile, **connection_args) ret['comment'] = 'Tenant / project "{0}" has been deleted'.format(name) ret['changes']['Tenant/Project'] = 'Deleted' return ret
[ "def", "tenant_absent", "(", "name", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'Tenant / proje...
Ensure that the keystone tenant is absent. name The name of the tenant that should not exist
[ "Ensure", "that", "the", "keystone", "tenant", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L402-L429
train
saltstack/salt
salt/states/keystone.py
project_present
def project_present(name, description=None, enabled=True, profile=None, **connection_args): ''' Ensures that the keystone project exists Alias for tenant_present from V2 API to fulfill V3 API naming convention. .. versionadded:: 2016.11.0 name The name of the project to manage description The description to use for this project enabled Availability state for this project .. code-block:: yaml nova: keystone.project_present: - enabled: True - description: 'Nova Compute Service' ''' return tenant_present(name, description=description, enabled=enabled, profile=profile, **connection_args)
python
def project_present(name, description=None, enabled=True, profile=None, **connection_args): ''' Ensures that the keystone project exists Alias for tenant_present from V2 API to fulfill V3 API naming convention. .. versionadded:: 2016.11.0 name The name of the project to manage description The description to use for this project enabled Availability state for this project .. code-block:: yaml nova: keystone.project_present: - enabled: True - description: 'Nova Compute Service' ''' return tenant_present(name, description=description, enabled=enabled, profile=profile, **connection_args)
[ "def", "project_present", "(", "name", ",", "description", "=", "None", ",", "enabled", "=", "True", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "return", "tenant_present", "(", "name", ",", "description", "=", "description", "...
Ensures that the keystone project exists Alias for tenant_present from V2 API to fulfill V3 API naming convention. .. versionadded:: 2016.11.0 name The name of the project to manage description The description to use for this project enabled Availability state for this project .. code-block:: yaml nova: keystone.project_present: - enabled: True - description: 'Nova Compute Service'
[ "Ensures", "that", "the", "keystone", "project", "exists", "Alias", "for", "tenant_present", "from", "V2", "API", "to", "fulfill", "V3", "API", "naming", "convention", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L432-L460
train
saltstack/salt
salt/states/keystone.py
role_present
def role_present(name, profile=None, **connection_args): '''' Ensures that the keystone role exists name The name of the role that should be present ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Role "{0}" already exists'.format(name)} # Check if role is already present role = __salt__['keystone.role_get'](name=name, profile=profile, **connection_args) if 'Error' not in role: return ret else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Role "{0}" will be added'.format(name) return ret # Create role __salt__['keystone.role_create'](name, profile=profile, **connection_args) ret['comment'] = 'Role "{0}" has been added'.format(name) ret['changes']['Role'] = 'Created' return ret
python
def role_present(name, profile=None, **connection_args): '''' Ensures that the keystone role exists name The name of the role that should be present ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Role "{0}" already exists'.format(name)} # Check if role is already present role = __salt__['keystone.role_get'](name=name, profile=profile, **connection_args) if 'Error' not in role: return ret else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Role "{0}" will be added'.format(name) return ret # Create role __salt__['keystone.role_create'](name, profile=profile, **connection_args) ret['comment'] = 'Role "{0}" has been added'.format(name) ret['changes']['Role'] = 'Created' return ret
[ "def", "role_present", "(", "name", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'Role \"{0}\" al...
Ensures that the keystone role exists name The name of the role that should be present
[ "Ensures", "that", "the", "keystone", "role", "exists" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L484-L512
train
saltstack/salt
salt/states/keystone.py
service_present
def service_present(name, service_type, description=None, profile=None, **connection_args): ''' Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the service ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Service "{0}" already exists'.format(name)} # Check if service is already present role = __salt__['keystone.service_get'](name=name, profile=profile, **connection_args) if 'Error' not in role: return ret else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Service "{0}" will be added'.format(name) return ret # Create service __salt__['keystone.service_create'](name, service_type, description, profile=profile, **connection_args) ret['comment'] = 'Service "{0}" has been added'.format(name) ret['changes']['Service'] = 'Created' return ret
python
def service_present(name, service_type, description=None, profile=None, **connection_args): ''' Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the service ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Service "{0}" already exists'.format(name)} # Check if service is already present role = __salt__['keystone.service_get'](name=name, profile=profile, **connection_args) if 'Error' not in role: return ret else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Service "{0}" will be added'.format(name) return ret # Create service __salt__['keystone.service_create'](name, service_type, description, profile=profile, **connection_args) ret['comment'] = 'Service "{0}" has been added'.format(name) ret['changes']['Service'] = 'Created' return ret
[ "def", "service_present", "(", "name", ",", "service_type", ",", "description", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result...
Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the service
[ "Ensure", "service", "present", "in", "Keystone", "catalog" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L544-L583
train
saltstack/salt
salt/states/keystone.py
endpoint_present
def endpoint_present(name, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Ensure the specified endpoints exists for service name The Service name publicurl The public url of service endpoint (for V2 API) internalurl The internal url of service endpoint (for V2 API) adminurl The admin url of the service endpoint (for V2 API) region The region of the endpoint url The endpoint URL (for V3 API) interface The interface type, which describes the visibility of the endpoint. (for V3 API) ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} _api_version(profile=profile, **connection_args) endpoint = __salt__['keystone.endpoint_get'](name, region, profile=profile, interface=interface, **connection_args) def _changes(desc): return ret.get('comment', '') + desc + '\n' def _create_endpoint(): if _OS_IDENTITY_API_VERSION > 2: ret['changes'] = __salt__['keystone.endpoint_create']( name, region=region, url=url, interface=interface, profile=profile, **connection_args) else: ret['changes'] = __salt__['keystone.endpoint_create']( name, region=region, publicurl=publicurl, adminurl=adminurl, internalurl=internalurl, profile=profile, **connection_args) if endpoint and 'Error' not in endpoint and endpoint.get('region') == region: if _OS_IDENTITY_API_VERSION > 2: change_url = False change_interface = False if endpoint.get('url', None) != url: ret['comment'] = _changes('URL changes from "{0}" to "{1}"'.format(endpoint.get('url', None), url)) change_url = True if endpoint.get('interface', None) != interface: ret['comment'] = _changes('Interface changes from "{0}" to "{1}"'.format(endpoint.get('interface', None), interface)) change_interface = True if __opts__.get('test') and (change_url or change_interface): ret['result'] = None ret['changes']['Endpoint'] = 'Will be updated' ret['comment'] += 'Endpoint for service "{0}" will be updated'.format(name) return ret if change_url: ret['changes']['url'] = url if change_interface: ret['changes']['interface'] = interface else: change_publicurl = False change_adminurl = False change_internalurl = False if endpoint.get('publicurl', None) != publicurl: change_publicurl = True ret['comment'] = _changes('Public URL changes from "{0}" to "{1}"'.format( endpoint.get('publicurl', None), publicurl) ) if endpoint.get('adminurl', None) != adminurl: change_adminurl = True ret['comment'] = _changes('Admin URL changes from "{0}" to "{1}"'.format( endpoint.get('adminurl', None), adminurl) ) if endpoint.get('internalurl', None) != internalurl: change_internalurl = True ret['comment'] = _changes( 'Internal URL changes from "{0}" to "{1}"'.format( endpoint.get('internalurl', None), internalurl ) ) if __opts__.get('test') and (change_publicurl or change_adminurl or change_internalurl): ret['result'] = None ret['comment'] += 'Endpoint for service "{0}" will be updated'.format(name) ret['changes']['Endpoint'] = 'Will be updated' return ret if change_publicurl: ret['changes']['publicurl'] = publicurl if change_adminurl: ret['changes']['adminurl'] = adminurl if change_internalurl: ret['changes']['internalurl'] = internalurl if ret['comment']: # changed __salt__['keystone.endpoint_delete'](name, region, profile=profile, interface=interface, **connection_args) _create_endpoint() ret['comment'] += 'Endpoint for service "{0}" has been updated'.format(name) else: # Add new endpoint if __opts__.get('test'): ret['result'] = None ret['changes']['Endpoint'] = 'Will be created' ret['comment'] = 'Endpoint for service "{0}" will be added'.format(name) return ret _create_endpoint() ret['comment'] = 'Endpoint for service "{0}" has been added'.format(name) if ret['comment'] == '': # => no changes ret['comment'] = 'Endpoint for service "{0}" already exists'.format(name) return ret
python
def endpoint_present(name, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Ensure the specified endpoints exists for service name The Service name publicurl The public url of service endpoint (for V2 API) internalurl The internal url of service endpoint (for V2 API) adminurl The admin url of the service endpoint (for V2 API) region The region of the endpoint url The endpoint URL (for V3 API) interface The interface type, which describes the visibility of the endpoint. (for V3 API) ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} _api_version(profile=profile, **connection_args) endpoint = __salt__['keystone.endpoint_get'](name, region, profile=profile, interface=interface, **connection_args) def _changes(desc): return ret.get('comment', '') + desc + '\n' def _create_endpoint(): if _OS_IDENTITY_API_VERSION > 2: ret['changes'] = __salt__['keystone.endpoint_create']( name, region=region, url=url, interface=interface, profile=profile, **connection_args) else: ret['changes'] = __salt__['keystone.endpoint_create']( name, region=region, publicurl=publicurl, adminurl=adminurl, internalurl=internalurl, profile=profile, **connection_args) if endpoint and 'Error' not in endpoint and endpoint.get('region') == region: if _OS_IDENTITY_API_VERSION > 2: change_url = False change_interface = False if endpoint.get('url', None) != url: ret['comment'] = _changes('URL changes from "{0}" to "{1}"'.format(endpoint.get('url', None), url)) change_url = True if endpoint.get('interface', None) != interface: ret['comment'] = _changes('Interface changes from "{0}" to "{1}"'.format(endpoint.get('interface', None), interface)) change_interface = True if __opts__.get('test') and (change_url or change_interface): ret['result'] = None ret['changes']['Endpoint'] = 'Will be updated' ret['comment'] += 'Endpoint for service "{0}" will be updated'.format(name) return ret if change_url: ret['changes']['url'] = url if change_interface: ret['changes']['interface'] = interface else: change_publicurl = False change_adminurl = False change_internalurl = False if endpoint.get('publicurl', None) != publicurl: change_publicurl = True ret['comment'] = _changes('Public URL changes from "{0}" to "{1}"'.format( endpoint.get('publicurl', None), publicurl) ) if endpoint.get('adminurl', None) != adminurl: change_adminurl = True ret['comment'] = _changes('Admin URL changes from "{0}" to "{1}"'.format( endpoint.get('adminurl', None), adminurl) ) if endpoint.get('internalurl', None) != internalurl: change_internalurl = True ret['comment'] = _changes( 'Internal URL changes from "{0}" to "{1}"'.format( endpoint.get('internalurl', None), internalurl ) ) if __opts__.get('test') and (change_publicurl or change_adminurl or change_internalurl): ret['result'] = None ret['comment'] += 'Endpoint for service "{0}" will be updated'.format(name) ret['changes']['Endpoint'] = 'Will be updated' return ret if change_publicurl: ret['changes']['publicurl'] = publicurl if change_adminurl: ret['changes']['adminurl'] = adminurl if change_internalurl: ret['changes']['internalurl'] = internalurl if ret['comment']: # changed __salt__['keystone.endpoint_delete'](name, region, profile=profile, interface=interface, **connection_args) _create_endpoint() ret['comment'] += 'Endpoint for service "{0}" has been updated'.format(name) else: # Add new endpoint if __opts__.get('test'): ret['result'] = None ret['changes']['Endpoint'] = 'Will be created' ret['comment'] = 'Endpoint for service "{0}" will be added'.format(name) return ret _create_endpoint() ret['comment'] = 'Endpoint for service "{0}" has been added'.format(name) if ret['comment'] == '': # => no changes ret['comment'] = 'Endpoint for service "{0}" already exists'.format(name) return ret
[ "def", "endpoint_present", "(", "name", ",", "publicurl", "=", "None", ",", "internalurl", "=", "None", ",", "adminurl", "=", "None", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "url", "=", "None", ",", "interface", "=", "None", ",", ...
Ensure the specified endpoints exists for service name The Service name publicurl The public url of service endpoint (for V2 API) internalurl The internal url of service endpoint (for V2 API) adminurl The admin url of the service endpoint (for V2 API) region The region of the endpoint url The endpoint URL (for V3 API) interface The interface type, which describes the visibility of the endpoint. (for V3 API)
[ "Ensure", "the", "specified", "endpoints", "exists", "for", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L617-L771
train
saltstack/salt
salt/states/keystone.py
endpoint_absent
def endpoint_absent(name, region=None, profile=None, interface=None, **connection_args): ''' Ensure that the endpoint for a service doesn't exist in Keystone catalog name The name of the service whose endpoints should not exist region (optional) The region of the endpoint. Defaults to ``RegionOne``. interface The interface type, which describes the visibility of the endpoint. (for V3 API) ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Endpoint for service "{0}"{1} is already absent'.format(name, ', interface "{0}",'.format(interface) if interface is not None else '')} # Check if service is present endpoint = __salt__['keystone.endpoint_get'](name, region, profile=profile, interface=interface, **connection_args) if not endpoint: return ret else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Endpoint for service "{0}" will be deleted'.format(name) return ret # Delete service __salt__['keystone.endpoint_delete'](name, region, profile=profile, interface=interface, **connection_args) ret['comment'] = 'Endpoint for service "{0}"{1} has been deleted'.format(name, ', interface "{0}",'.format(interface) if interface is not None else '') ret['changes']['endpoint'] = 'Deleted' return ret
python
def endpoint_absent(name, region=None, profile=None, interface=None, **connection_args): ''' Ensure that the endpoint for a service doesn't exist in Keystone catalog name The name of the service whose endpoints should not exist region (optional) The region of the endpoint. Defaults to ``RegionOne``. interface The interface type, which describes the visibility of the endpoint. (for V3 API) ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Endpoint for service "{0}"{1} is already absent'.format(name, ', interface "{0}",'.format(interface) if interface is not None else '')} # Check if service is present endpoint = __salt__['keystone.endpoint_get'](name, region, profile=profile, interface=interface, **connection_args) if not endpoint: return ret else: if __opts__.get('test'): ret['result'] = None ret['comment'] = 'Endpoint for service "{0}" will be deleted'.format(name) return ret # Delete service __salt__['keystone.endpoint_delete'](name, region, profile=profile, interface=interface, **connection_args) ret['comment'] = 'Endpoint for service "{0}"{1} has been deleted'.format(name, ', interface "{0}",'.format(interface) if interface is not None else '') ret['changes']['endpoint'] = 'Deleted' return ret
[ "def", "endpoint_absent", "(", "name", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "interface", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", ...
Ensure that the endpoint for a service doesn't exist in Keystone catalog name The name of the service whose endpoints should not exist region (optional) The region of the endpoint. Defaults to ``RegionOne``. interface The interface type, which describes the visibility of the endpoint. (for V3 API)
[ "Ensure", "that", "the", "endpoint", "for", "a", "service", "doesn", "t", "exist", "in", "Keystone", "catalog" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone.py#L774-L814
train
saltstack/salt
salt/modules/rh_service.py
_chkconfig_add
def _chkconfig_add(name): ''' Run 'chkconfig --add' for a service whose script is installed in /etc/init.d. The service is initially configured to be disabled at all run-levels. ''' cmd = '/sbin/chkconfig --add {0}'.format(name) if __salt__['cmd.retcode'](cmd, python_shell=False) == 0: log.info('Added initscript "%s" to chkconfig', name) return True else: log.error('Unable to add initscript "%s" to chkconfig', name) return False
python
def _chkconfig_add(name): ''' Run 'chkconfig --add' for a service whose script is installed in /etc/init.d. The service is initially configured to be disabled at all run-levels. ''' cmd = '/sbin/chkconfig --add {0}'.format(name) if __salt__['cmd.retcode'](cmd, python_shell=False) == 0: log.info('Added initscript "%s" to chkconfig', name) return True else: log.error('Unable to add initscript "%s" to chkconfig', name) return False
[ "def", "_chkconfig_add", "(", "name", ")", ":", "cmd", "=", "'/sbin/chkconfig --add {0}'", ".", "format", "(", "name", ")", "if", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", "==", "0", ":", "log", ".", "info...
Run 'chkconfig --add' for a service whose script is installed in /etc/init.d. The service is initially configured to be disabled at all run-levels.
[ "Run", "chkconfig", "--", "add", "for", "a", "service", "whose", "script", "is", "installed", "in", "/", "etc", "/", "init", ".", "d", ".", "The", "service", "is", "initially", "configured", "to", "be", "disabled", "at", "all", "run", "-", "levels", "....
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L126-L138
train
saltstack/salt
salt/modules/rh_service.py
_service_is_sysv
def _service_is_sysv(name): ''' Return True if the service is a System V service (includes those managed by chkconfig); otherwise return False. ''' try: # Look for user-execute bit in file mode. return bool(os.stat( os.path.join('/etc/init.d', name)).st_mode & stat.S_IXUSR) except OSError: return False
python
def _service_is_sysv(name): ''' Return True if the service is a System V service (includes those managed by chkconfig); otherwise return False. ''' try: # Look for user-execute bit in file mode. return bool(os.stat( os.path.join('/etc/init.d', name)).st_mode & stat.S_IXUSR) except OSError: return False
[ "def", "_service_is_sysv", "(", "name", ")", ":", "try", ":", "# Look for user-execute bit in file mode.", "return", "bool", "(", "os", ".", "stat", "(", "os", ".", "path", ".", "join", "(", "'/etc/init.d'", ",", "name", ")", ")", ".", "st_mode", "&", "sta...
Return True if the service is a System V service (includes those managed by chkconfig); otherwise return False.
[ "Return", "True", "if", "the", "service", "is", "a", "System", "V", "service", "(", "includes", "those", "managed", "by", "chkconfig", ")", ";", "otherwise", "return", "False", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L148-L158
train
saltstack/salt
salt/modules/rh_service.py
_service_is_chkconfig
def _service_is_chkconfig(name): ''' Return True if the service is managed by chkconfig. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) return __salt__['cmd.retcode'](cmdline, python_shell=False, ignore_retcode=True) == 0
python
def _service_is_chkconfig(name): ''' Return True if the service is managed by chkconfig. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) return __salt__['cmd.retcode'](cmdline, python_shell=False, ignore_retcode=True) == 0
[ "def", "_service_is_chkconfig", "(", "name", ")", ":", "cmdline", "=", "'/sbin/chkconfig --list {0}'", ".", "format", "(", "name", ")", "return", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmdline", ",", "python_shell", "=", "False", ",", "ignore_retcode", "="...
Return True if the service is managed by chkconfig.
[ "Return", "True", "if", "the", "service", "is", "managed", "by", "chkconfig", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L161-L166
train
saltstack/salt
salt/modules/rh_service.py
_sysv_is_enabled
def _sysv_is_enabled(name, runlevel=None): ''' Return True if the sysv (or chkconfig) service is enabled for the specified runlevel; otherwise return False. If `runlevel` is None, then use the current runlevel. ''' # Try chkconfig first. result = _chkconfig_is_enabled(name, runlevel) if result: return True if runlevel is None: runlevel = _runlevel() return ( len(glob.glob('/etc/rc.d/rc{0}.d/S??{1}'.format(runlevel, name))) > 0)
python
def _sysv_is_enabled(name, runlevel=None): ''' Return True if the sysv (or chkconfig) service is enabled for the specified runlevel; otherwise return False. If `runlevel` is None, then use the current runlevel. ''' # Try chkconfig first. result = _chkconfig_is_enabled(name, runlevel) if result: return True if runlevel is None: runlevel = _runlevel() return ( len(glob.glob('/etc/rc.d/rc{0}.d/S??{1}'.format(runlevel, name))) > 0)
[ "def", "_sysv_is_enabled", "(", "name", ",", "runlevel", "=", "None", ")", ":", "# Try chkconfig first.", "result", "=", "_chkconfig_is_enabled", "(", "name", ",", "runlevel", ")", "if", "result", ":", "return", "True", "if", "runlevel", "is", "None", ":", "...
Return True if the sysv (or chkconfig) service is enabled for the specified runlevel; otherwise return False. If `runlevel` is None, then use the current runlevel.
[ "Return", "True", "if", "the", "sysv", "(", "or", "chkconfig", ")", "service", "is", "enabled", "for", "the", "specified", "runlevel", ";", "otherwise", "return", "False", ".", "If", "runlevel", "is", "None", "then", "use", "the", "current", "runlevel", "....
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L169-L183
train
saltstack/salt
salt/modules/rh_service.py
_chkconfig_is_enabled
def _chkconfig_is_enabled(name, runlevel=None): ''' Return ``True`` if the service is enabled according to chkconfig; otherwise return ``False``. If ``runlevel`` is ``None``, then use the current runlevel. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) result = __salt__['cmd.run_all'](cmdline, python_shell=False) if runlevel is None: runlevel = _runlevel() if result['retcode'] == 0: for row in result['stdout'].splitlines(): if '{0}:on'.format(runlevel) in row: if row.split()[0] == name: return True elif row.split() == [name, 'on']: return True return False
python
def _chkconfig_is_enabled(name, runlevel=None): ''' Return ``True`` if the service is enabled according to chkconfig; otherwise return ``False``. If ``runlevel`` is ``None``, then use the current runlevel. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) result = __salt__['cmd.run_all'](cmdline, python_shell=False) if runlevel is None: runlevel = _runlevel() if result['retcode'] == 0: for row in result['stdout'].splitlines(): if '{0}:on'.format(runlevel) in row: if row.split()[0] == name: return True elif row.split() == [name, 'on']: return True return False
[ "def", "_chkconfig_is_enabled", "(", "name", ",", "runlevel", "=", "None", ")", ":", "cmdline", "=", "'/sbin/chkconfig --list {0}'", ".", "format", "(", "name", ")", "result", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmdline", ",", "python_shell", "="...
Return ``True`` if the service is enabled according to chkconfig; otherwise return ``False``. If ``runlevel`` is ``None``, then use the current runlevel.
[ "Return", "True", "if", "the", "service", "is", "enabled", "according", "to", "chkconfig", ";", "otherwise", "return", "False", ".", "If", "runlevel", "is", "None", "then", "use", "the", "current", "runlevel", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L186-L204
train
saltstack/salt
salt/modules/rh_service.py
_sysv_enable
def _sysv_enable(name): ''' Enable the named sysv service to start at boot. The service will be enabled using chkconfig with default run-levels if the service is chkconfig compatible. If chkconfig is not available, then this will fail. ''' if not _service_is_chkconfig(name) and not _chkconfig_add(name): return False cmd = '/sbin/chkconfig {0} on'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
python
def _sysv_enable(name): ''' Enable the named sysv service to start at boot. The service will be enabled using chkconfig with default run-levels if the service is chkconfig compatible. If chkconfig is not available, then this will fail. ''' if not _service_is_chkconfig(name) and not _chkconfig_add(name): return False cmd = '/sbin/chkconfig {0} on'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
[ "def", "_sysv_enable", "(", "name", ")", ":", "if", "not", "_service_is_chkconfig", "(", "name", ")", "and", "not", "_chkconfig_add", "(", "name", ")", ":", "return", "False", "cmd", "=", "'/sbin/chkconfig {0} on'", ".", "format", "(", "name", ")", "return",...
Enable the named sysv service to start at boot. The service will be enabled using chkconfig with default run-levels if the service is chkconfig compatible. If chkconfig is not available, then this will fail.
[ "Enable", "the", "named", "sysv", "service", "to", "start", "at", "boot", ".", "The", "service", "will", "be", "enabled", "using", "chkconfig", "with", "default", "run", "-", "levels", "if", "the", "service", "is", "chkconfig", "compatible", ".", "If", "ch...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L207-L216
train
saltstack/salt
salt/modules/rh_service.py
_sysv_delete
def _sysv_delete(name): ''' Delete the named sysv service from the system. The service will be deleted using chkconfig. ''' if not _service_is_chkconfig(name): return False cmd = '/sbin/chkconfig --del {0}'.format(name) return not __salt__['cmd.retcode'](cmd)
python
def _sysv_delete(name): ''' Delete the named sysv service from the system. The service will be deleted using chkconfig. ''' if not _service_is_chkconfig(name): return False cmd = '/sbin/chkconfig --del {0}'.format(name) return not __salt__['cmd.retcode'](cmd)
[ "def", "_sysv_delete", "(", "name", ")", ":", "if", "not", "_service_is_chkconfig", "(", "name", ")", ":", "return", "False", "cmd", "=", "'/sbin/chkconfig --del {0}'", ".", "format", "(", "name", ")", "return", "not", "__salt__", "[", "'cmd.retcode'", "]", ...
Delete the named sysv service from the system. The service will be deleted using chkconfig.
[ "Delete", "the", "named", "sysv", "service", "from", "the", "system", ".", "The", "service", "will", "be", "deleted", "using", "chkconfig", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L232-L240
train
saltstack/salt
salt/modules/rh_service.py
_upstart_delete
def _upstart_delete(name): ''' Delete an upstart service. This will only rename the .conf file ''' if HAS_UPSTART: if os.path.exists('/etc/init/{0}.conf'.format(name)): os.rename('/etc/init/{0}.conf'.format(name), '/etc/init/{0}.conf.removed'.format(name)) return True
python
def _upstart_delete(name): ''' Delete an upstart service. This will only rename the .conf file ''' if HAS_UPSTART: if os.path.exists('/etc/init/{0}.conf'.format(name)): os.rename('/etc/init/{0}.conf'.format(name), '/etc/init/{0}.conf.removed'.format(name)) return True
[ "def", "_upstart_delete", "(", "name", ")", ":", "if", "HAS_UPSTART", ":", "if", "os", ".", "path", ".", "exists", "(", "'/etc/init/{0}.conf'", ".", "format", "(", "name", ")", ")", ":", "os", ".", "rename", "(", "'/etc/init/{0}.conf'", ".", "format", "(...
Delete an upstart service. This will only rename the .conf file
[ "Delete", "an", "upstart", "service", ".", "This", "will", "only", "rename", "the", ".", "conf", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L243-L251
train
saltstack/salt
salt/modules/rh_service.py
_sysv_services
def _sysv_services(): ''' Return list of sysv services. ''' _services = [] output = __salt__['cmd.run'](['chkconfig', '--list'], python_shell=False) for line in output.splitlines(): comps = line.split() try: if comps[1].startswith('0:'): _services.append(comps[0]) except IndexError: continue # Return only the services that have an initscript present return [x for x in _services if _service_is_sysv(x)]
python
def _sysv_services(): ''' Return list of sysv services. ''' _services = [] output = __salt__['cmd.run'](['chkconfig', '--list'], python_shell=False) for line in output.splitlines(): comps = line.split() try: if comps[1].startswith('0:'): _services.append(comps[0]) except IndexError: continue # Return only the services that have an initscript present return [x for x in _services if _service_is_sysv(x)]
[ "def", "_sysv_services", "(", ")", ":", "_services", "=", "[", "]", "output", "=", "__salt__", "[", "'cmd.run'", "]", "(", "[", "'chkconfig'", ",", "'--list'", "]", ",", "python_shell", "=", "False", ")", "for", "line", "in", "output", ".", "splitlines",...
Return list of sysv services.
[ "Return", "list", "of", "sysv", "services", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L265-L279
train
saltstack/salt
salt/modules/rh_service.py
get_enabled
def get_enabled(limit=''): ''' Return the enabled services. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.get_enabled salt '*' service.get_enabled limit=upstart salt '*' service.get_enabled limit=sysvinit ''' limit = limit.lower() if limit == 'upstart': return sorted(name for name in _upstart_services() if _upstart_is_enabled(name)) elif limit == 'sysvinit': runlevel = _runlevel() return sorted(name for name in _sysv_services() if _sysv_is_enabled(name, runlevel)) else: runlevel = _runlevel() return sorted( [name for name in _upstart_services() if _upstart_is_enabled(name)] + [name for name in _sysv_services() if _sysv_is_enabled(name, runlevel)])
python
def get_enabled(limit=''): ''' Return the enabled services. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.get_enabled salt '*' service.get_enabled limit=upstart salt '*' service.get_enabled limit=sysvinit ''' limit = limit.lower() if limit == 'upstart': return sorted(name for name in _upstart_services() if _upstart_is_enabled(name)) elif limit == 'sysvinit': runlevel = _runlevel() return sorted(name for name in _sysv_services() if _sysv_is_enabled(name, runlevel)) else: runlevel = _runlevel() return sorted( [name for name in _upstart_services() if _upstart_is_enabled(name)] + [name for name in _sysv_services() if _sysv_is_enabled(name, runlevel)])
[ "def", "get_enabled", "(", "limit", "=", "''", ")", ":", "limit", "=", "limit", ".", "lower", "(", ")", "if", "limit", "==", "'upstart'", ":", "return", "sorted", "(", "name", "for", "name", "in", "_upstart_services", "(", ")", "if", "_upstart_is_enabled...
Return the enabled services. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.get_enabled salt '*' service.get_enabled limit=upstart salt '*' service.get_enabled limit=sysvinit
[ "Return", "the", "enabled", "services", ".", "Use", "the", "limit", "param", "to", "restrict", "results", "to", "services", "of", "that", "type", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L282-L309
train
saltstack/salt
salt/modules/rh_service.py
get_all
def get_all(limit=''): ''' Return all installed services. Use the ``limit`` param to restrict results to services of that type. CLI Example: .. code-block:: bash salt '*' service.get_all salt '*' service.get_all limit=upstart salt '*' service.get_all limit=sysvinit ''' limit = limit.lower() if limit == 'upstart': return sorted(_upstart_services()) elif limit == 'sysvinit': return sorted(_sysv_services()) else: return sorted(_sysv_services() + _upstart_services())
python
def get_all(limit=''): ''' Return all installed services. Use the ``limit`` param to restrict results to services of that type. CLI Example: .. code-block:: bash salt '*' service.get_all salt '*' service.get_all limit=upstart salt '*' service.get_all limit=sysvinit ''' limit = limit.lower() if limit == 'upstart': return sorted(_upstart_services()) elif limit == 'sysvinit': return sorted(_sysv_services()) else: return sorted(_sysv_services() + _upstart_services())
[ "def", "get_all", "(", "limit", "=", "''", ")", ":", "limit", "=", "limit", ".", "lower", "(", ")", "if", "limit", "==", "'upstart'", ":", "return", "sorted", "(", "_upstart_services", "(", ")", ")", "elif", "limit", "==", "'sysvinit'", ":", "return", ...
Return all installed services. Use the ``limit`` param to restrict results to services of that type. CLI Example: .. code-block:: bash salt '*' service.get_all salt '*' service.get_all limit=upstart salt '*' service.get_all limit=sysvinit
[ "Return", "all", "installed", "services", ".", "Use", "the", "limit", "param", "to", "restrict", "results", "to", "services", "of", "that", "type", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L342-L361
train
saltstack/salt
salt/modules/rh_service.py
available
def available(name, limit=''): ''' Return True if the named service is available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.available sshd salt '*' service.available sshd limit=upstart salt '*' service.available sshd limit=sysvinit ''' if limit == 'upstart': return _service_is_upstart(name) elif limit == 'sysvinit': return _service_is_sysv(name) else: return _service_is_upstart(name) or _service_is_sysv(name) or _service_is_chkconfig(name)
python
def available(name, limit=''): ''' Return True if the named service is available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.available sshd salt '*' service.available sshd limit=upstart salt '*' service.available sshd limit=sysvinit ''' if limit == 'upstart': return _service_is_upstart(name) elif limit == 'sysvinit': return _service_is_sysv(name) else: return _service_is_upstart(name) or _service_is_sysv(name) or _service_is_chkconfig(name)
[ "def", "available", "(", "name", ",", "limit", "=", "''", ")", ":", "if", "limit", "==", "'upstart'", ":", "return", "_service_is_upstart", "(", "name", ")", "elif", "limit", "==", "'sysvinit'", ":", "return", "_service_is_sysv", "(", "name", ")", "else", ...
Return True if the named service is available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.available sshd salt '*' service.available sshd limit=upstart salt '*' service.available sshd limit=sysvinit
[ "Return", "True", "if", "the", "named", "service", "is", "available", ".", "Use", "the", "limit", "param", "to", "restrict", "results", "to", "services", "of", "that", "type", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L364-L382
train
saltstack/salt
salt/modules/rh_service.py
missing
def missing(name, limit=''): ''' The inverse of service.available. Return True if the named service is not available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.missing sshd salt '*' service.missing sshd limit=upstart salt '*' service.missing sshd limit=sysvinit ''' if limit == 'upstart': return not _service_is_upstart(name) elif limit == 'sysvinit': return not _service_is_sysv(name) else: if _service_is_upstart(name) or _service_is_sysv(name): return False else: return True
python
def missing(name, limit=''): ''' The inverse of service.available. Return True if the named service is not available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.missing sshd salt '*' service.missing sshd limit=upstart salt '*' service.missing sshd limit=sysvinit ''' if limit == 'upstart': return not _service_is_upstart(name) elif limit == 'sysvinit': return not _service_is_sysv(name) else: if _service_is_upstart(name) or _service_is_sysv(name): return False else: return True
[ "def", "missing", "(", "name", ",", "limit", "=", "''", ")", ":", "if", "limit", "==", "'upstart'", ":", "return", "not", "_service_is_upstart", "(", "name", ")", "elif", "limit", "==", "'sysvinit'", ":", "return", "not", "_service_is_sysv", "(", "name", ...
The inverse of service.available. Return True if the named service is not available. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.missing sshd salt '*' service.missing sshd limit=upstart salt '*' service.missing sshd limit=sysvinit
[ "The", "inverse", "of", "service", ".", "available", ".", "Return", "True", "if", "the", "named", "service", "is", "not", "available", ".", "Use", "the", "limit", "param", "to", "restrict", "results", "to", "services", "of", "that", "type", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L385-L407
train
saltstack/salt
salt/modules/rh_service.py
start
def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' if _service_is_upstart(name): cmd = 'start {0}'.format(name) else: cmd = '/sbin/service {0} start'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
python
def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' if _service_is_upstart(name): cmd = 'start {0}'.format(name) else: cmd = '/sbin/service {0} start'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
[ "def", "start", "(", "name", ")", ":", "if", "_service_is_upstart", "(", "name", ")", ":", "cmd", "=", "'start {0}'", ".", "format", "(", "name", ")", "else", ":", "cmd", "=", "'/sbin/service {0} start'", ".", "format", "(", "name", ")", "return", "not",...
Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name>
[ "Start", "the", "specified", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L410-L424
train
saltstack/salt
salt/modules/rh_service.py
stop
def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' if _service_is_upstart(name): cmd = 'stop {0}'.format(name) else: cmd = '/sbin/service {0} stop'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
python
def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' if _service_is_upstart(name): cmd = 'stop {0}'.format(name) else: cmd = '/sbin/service {0} stop'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
[ "def", "stop", "(", "name", ")", ":", "if", "_service_is_upstart", "(", "name", ")", ":", "cmd", "=", "'stop {0}'", ".", "format", "(", "name", ")", "else", ":", "cmd", "=", "'/sbin/service {0} stop'", ".", "format", "(", "name", ")", "return", "not", ...
Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name>
[ "Stop", "the", "specified", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L427-L441
train
saltstack/salt
salt/modules/rh_service.py
restart
def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if _service_is_upstart(name): cmd = 'restart {0}'.format(name) else: cmd = '/sbin/service {0} restart'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
python
def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if _service_is_upstart(name): cmd = 'restart {0}'.format(name) else: cmd = '/sbin/service {0} restart'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
[ "def", "restart", "(", "name", ")", ":", "if", "_service_is_upstart", "(", "name", ")", ":", "cmd", "=", "'restart {0}'", ".", "format", "(", "name", ")", "else", ":", "cmd", "=", "'/sbin/service {0} restart'", ".", "format", "(", "name", ")", "return", ...
Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name>
[ "Restart", "the", "named", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L444-L458
train
saltstack/salt
salt/modules/rh_service.py
reload_
def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' if _service_is_upstart(name): cmd = 'reload {0}'.format(name) else: cmd = '/sbin/service {0} reload'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
python
def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' if _service_is_upstart(name): cmd = 'reload {0}'.format(name) else: cmd = '/sbin/service {0} reload'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
[ "def", "reload_", "(", "name", ")", ":", "if", "_service_is_upstart", "(", "name", ")", ":", "cmd", "=", "'reload {0}'", ".", "format", "(", "name", ")", "else", ":", "cmd", "=", "'/sbin/service {0} reload'", ".", "format", "(", "name", ")", "return", "n...
Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name>
[ "Reload", "the", "named", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L461-L475
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
_check_repo_sign_utils_support
def _check_repo_sign_utils_support(name): ''' Check for specified command name in search path ''' if salt.utils.path.which(name): return True else: raise CommandExecutionError( 'utility \'{0}\' needs to be installed or made available in search path'.format(name) )
python
def _check_repo_sign_utils_support(name): ''' Check for specified command name in search path ''' if salt.utils.path.which(name): return True else: raise CommandExecutionError( 'utility \'{0}\' needs to be installed or made available in search path'.format(name) )
[ "def", "_check_repo_sign_utils_support", "(", "name", ")", ":", "if", "salt", ".", "utils", ".", "path", ".", "which", "(", "name", ")", ":", "return", "True", "else", ":", "raise", "CommandExecutionError", "(", "'utility \\'{0}\\' needs to be installed or made avai...
Check for specified command name in search path
[ "Check", "for", "specified", "command", "name", "in", "search", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L73-L82
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
_get_build_env
def _get_build_env(env): ''' Get build environment overrides dictionary to use in build process ''' env_override = '' if env is None: return env_override if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for key, value in env.items(): env_override += '{0}={1}\n'.format(key, value) env_override += 'export {0}\n'.format(key) return env_override
python
def _get_build_env(env): ''' Get build environment overrides dictionary to use in build process ''' env_override = '' if env is None: return env_override if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for key, value in env.items(): env_override += '{0}={1}\n'.format(key, value) env_override += 'export {0}\n'.format(key) return env_override
[ "def", "_get_build_env", "(", "env", ")", ":", "env_override", "=", "''", "if", "env", "is", "None", ":", "return", "env_override", "if", "not", "isinstance", "(", "env", ",", "dict", ")", ":", "raise", "SaltInvocationError", "(", "'\\'env\\' must be a Python ...
Get build environment overrides dictionary to use in build process
[ "Get", "build", "environment", "overrides", "dictionary", "to", "use", "in", "build", "process" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L98-L112
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
_get_repo_options_env
def _get_repo_options_env(env): ''' Get repo environment overrides dictionary to use in repo options process env A dictionary of variables to define the repository options Example: .. code-block:: yaml - env: - OPTIONS : 'ask-passphrase' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. ''' env_options = '' if env is None: return env_options if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for key, value in env.items(): if key == 'OPTIONS': env_options += '{0}\n'.format(value) return env_options
python
def _get_repo_options_env(env): ''' Get repo environment overrides dictionary to use in repo options process env A dictionary of variables to define the repository options Example: .. code-block:: yaml - env: - OPTIONS : 'ask-passphrase' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. ''' env_options = '' if env is None: return env_options if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for key, value in env.items(): if key == 'OPTIONS': env_options += '{0}\n'.format(value) return env_options
[ "def", "_get_repo_options_env", "(", "env", ")", ":", "env_options", "=", "''", "if", "env", "is", "None", ":", "return", "env_options", "if", "not", "isinstance", "(", "env", ",", "dict", ")", ":", "raise", "SaltInvocationError", "(", "'\\'env\\' must be a Py...
Get repo environment overrides dictionary to use in repo options process env A dictionary of variables to define the repository options Example: .. code-block:: yaml - env: - OPTIONS : 'ask-passphrase' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
[ "Get", "repo", "environment", "overrides", "dictionary", "to", "use", "in", "repo", "options", "process" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L115-L147
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
_get_repo_dists_env
def _get_repo_dists_env(env): ''' Get repo environment overrides dictionary to use in repo distributions process env A dictionary of variables to define the repository distributions Example: .. code-block:: yaml - env: - ORIGIN : 'jessie' - LABEL : 'salt debian' - SUITE : 'main' - VERSION : '8.1' - CODENAME : 'jessie' - ARCHS : 'amd64 i386 source' - COMPONENTS : 'main' - DESCRIPTION : 'SaltStack Debian package repo' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. ''' # env key with tuple of control information for handling input env dictionary # 0 | M - Mandatory, O - Optional, I - Ignore # 1 | 'text string for repo field' # 2 | 'default value' dflts_dict = { 'OPTIONS': ('I', '', 'processed by _get_repo_options_env'), 'ORIGIN': ('O', 'Origin', 'SaltStack'), 'LABEL': ('O', 'Label', 'salt_debian'), 'SUITE': ('O', 'Suite', 'stable'), 'VERSION': ('O', 'Version', '9.0'), 'CODENAME': ('M', 'Codename', 'stretch'), 'ARCHS': ('M', 'Architectures', 'i386 amd64 source'), 'COMPONENTS': ('M', 'Components', 'main'), 'DESCRIPTION': ('O', 'Description', 'SaltStack debian package repo'), } env_dists = '' codename = '' dflts_keys = list(dflts_dict.keys()) if env is None: for key, value in dflts_dict.items(): if dflts_dict[key][0] == 'M': env_dists += '{0}: {1}\n'.format(dflts_dict[key][1], dflts_dict[key][2]) if key == 'CODENAME': codename = dflts_dict[key][2] return (codename, env_dists) if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) env_man_seen = [] for key, value in env.items(): if key in dflts_keys: if dflts_dict[key][0] == 'M': env_man_seen.append(key) if key == 'CODENAME': codename = value if dflts_dict[key][0] != 'I': env_dists += '{0}: {1}\n'.format(dflts_dict[key][1], value) else: env_dists += '{0}: {1}\n'.format(key, value) # ensure mandatories are included env_keys = list(env.keys()) for key in env_keys: if key in dflts_keys and dflts_dict[key][0] == 'M' and key not in env_man_seen: env_dists += '{0}: {1}\n'.format(dflts_dict[key][1], dflts_dict[key][2]) if key == 'CODENAME': codename = value return (codename, env_dists)
python
def _get_repo_dists_env(env): ''' Get repo environment overrides dictionary to use in repo distributions process env A dictionary of variables to define the repository distributions Example: .. code-block:: yaml - env: - ORIGIN : 'jessie' - LABEL : 'salt debian' - SUITE : 'main' - VERSION : '8.1' - CODENAME : 'jessie' - ARCHS : 'amd64 i386 source' - COMPONENTS : 'main' - DESCRIPTION : 'SaltStack Debian package repo' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. ''' # env key with tuple of control information for handling input env dictionary # 0 | M - Mandatory, O - Optional, I - Ignore # 1 | 'text string for repo field' # 2 | 'default value' dflts_dict = { 'OPTIONS': ('I', '', 'processed by _get_repo_options_env'), 'ORIGIN': ('O', 'Origin', 'SaltStack'), 'LABEL': ('O', 'Label', 'salt_debian'), 'SUITE': ('O', 'Suite', 'stable'), 'VERSION': ('O', 'Version', '9.0'), 'CODENAME': ('M', 'Codename', 'stretch'), 'ARCHS': ('M', 'Architectures', 'i386 amd64 source'), 'COMPONENTS': ('M', 'Components', 'main'), 'DESCRIPTION': ('O', 'Description', 'SaltStack debian package repo'), } env_dists = '' codename = '' dflts_keys = list(dflts_dict.keys()) if env is None: for key, value in dflts_dict.items(): if dflts_dict[key][0] == 'M': env_dists += '{0}: {1}\n'.format(dflts_dict[key][1], dflts_dict[key][2]) if key == 'CODENAME': codename = dflts_dict[key][2] return (codename, env_dists) if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) env_man_seen = [] for key, value in env.items(): if key in dflts_keys: if dflts_dict[key][0] == 'M': env_man_seen.append(key) if key == 'CODENAME': codename = value if dflts_dict[key][0] != 'I': env_dists += '{0}: {1}\n'.format(dflts_dict[key][1], value) else: env_dists += '{0}: {1}\n'.format(key, value) # ensure mandatories are included env_keys = list(env.keys()) for key in env_keys: if key in dflts_keys and dflts_dict[key][0] == 'M' and key not in env_man_seen: env_dists += '{0}: {1}\n'.format(dflts_dict[key][1], dflts_dict[key][2]) if key == 'CODENAME': codename = value return (codename, env_dists)
[ "def", "_get_repo_dists_env", "(", "env", ")", ":", "# env key with tuple of control information for handling input env dictionary", "# 0 | M - Mandatory, O - Optional, I - Ignore", "# 1 | 'text string for repo field'", "# 2 | 'default value'", "dflts_dict", "=", "{", "'OPTIONS'", ":", ...
Get repo environment overrides dictionary to use in repo distributions process env A dictionary of variables to define the repository distributions Example: .. code-block:: yaml - env: - ORIGIN : 'jessie' - LABEL : 'salt debian' - SUITE : 'main' - VERSION : '8.1' - CODENAME : 'jessie' - ARCHS : 'amd64 i386 source' - COMPONENTS : 'main' - DESCRIPTION : 'SaltStack Debian package repo' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
[ "Get", "repo", "environment", "overrides", "dictionary", "to", "use", "in", "repo", "distributions", "process" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L150-L231
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
_create_pbuilders
def _create_pbuilders(env, runas='root'): ''' Create the .pbuilder family of files in user's home directory env A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'nocheck' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. runas : root .. versionadded:: fluorine User to create the files and directories .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized. ''' home = os.path.expanduser('~{0}'.format(runas)) pbuilderrc = os.path.join(home, '.pbuilderrc') if not os.path.isfile(pbuilderrc): raise SaltInvocationError( 'pbuilderrc environment is incorrectly setup' ) env_overrides = _get_build_env(env) if env_overrides and not env_overrides.isspace(): with salt.utils.files.fopen(pbuilderrc, 'a') as fow: fow.write(salt.utils.stringutils.to_str(env_overrides)) cmd = "chown {0}:{0} {1}".format(runas, pbuilderrc) retrc = __salt__['cmd.retcode'](cmd, runas='root') if retrc != 0: raise SaltInvocationError( "Create pbuilderrc in home directory failed with return error \'{0}\', " "check logs for further details".format( retrc) )
python
def _create_pbuilders(env, runas='root'): ''' Create the .pbuilder family of files in user's home directory env A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'nocheck' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. runas : root .. versionadded:: fluorine User to create the files and directories .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized. ''' home = os.path.expanduser('~{0}'.format(runas)) pbuilderrc = os.path.join(home, '.pbuilderrc') if not os.path.isfile(pbuilderrc): raise SaltInvocationError( 'pbuilderrc environment is incorrectly setup' ) env_overrides = _get_build_env(env) if env_overrides and not env_overrides.isspace(): with salt.utils.files.fopen(pbuilderrc, 'a') as fow: fow.write(salt.utils.stringutils.to_str(env_overrides)) cmd = "chown {0}:{0} {1}".format(runas, pbuilderrc) retrc = __salt__['cmd.retcode'](cmd, runas='root') if retrc != 0: raise SaltInvocationError( "Create pbuilderrc in home directory failed with return error \'{0}\', " "check logs for further details".format( retrc) )
[ "def", "_create_pbuilders", "(", "env", ",", "runas", "=", "'root'", ")", ":", "home", "=", "os", ".", "path", ".", "expanduser", "(", "'~{0}'", ".", "format", "(", "runas", ")", ")", "pbuilderrc", "=", "os", ".", "path", ".", "join", "(", "home", ...
Create the .pbuilder family of files in user's home directory env A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'nocheck' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. runas : root .. versionadded:: fluorine User to create the files and directories .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized.
[ "Create", "the", ".", "pbuilder", "family", "of", "files", "in", "user", "s", "home", "directory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L234-L283
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
_get_src
def _get_src(tree_base, source, saltenv='base'): ''' Get the named sources and place them into the tree_base ''' parsed = _urlparse(source) sbase = os.path.basename(source) dest = os.path.join(tree_base, sbase) if parsed.scheme: __salt__['cp.get_url'](source, dest, saltenv=saltenv) else: shutil.copy(source, dest)
python
def _get_src(tree_base, source, saltenv='base'): ''' Get the named sources and place them into the tree_base ''' parsed = _urlparse(source) sbase = os.path.basename(source) dest = os.path.join(tree_base, sbase) if parsed.scheme: __salt__['cp.get_url'](source, dest, saltenv=saltenv) else: shutil.copy(source, dest)
[ "def", "_get_src", "(", "tree_base", ",", "source", ",", "saltenv", "=", "'base'", ")", ":", "parsed", "=", "_urlparse", "(", "source", ")", "sbase", "=", "os", ".", "path", ".", "basename", "(", "source", ")", "dest", "=", "os", ".", "path", ".", ...
Get the named sources and place them into the tree_base
[ "Get", "the", "named", "sources", "and", "place", "them", "into", "the", "tree_base" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L305-L315
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
make_src_pkg
def make_src_pkg(dest_dir, spec, sources, env=None, saltenv='base', runas='root'): ''' Create a platform specific source package from the given platform spec/control file and sources CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control.tar.xz https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl SOURCE package and place it in /var/www/html/ on the minion dest_dir Absolute path for directory to write source package spec Absolute path to spec file or equivalent sources Absolute path to source files to build source package from env : None A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'nocheck' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. saltenv: base Salt environment variables runas : root .. versionadded:: fluorine User to create the files and directories .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized. ''' _create_pbuilders(env, runas) tree_base = _mk_tree() ret = [] if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # ensure directories are writable root_user = 'root' retrc = 0 cmd = "chown {0}:{0} {1}".format(runas, tree_base) retrc = __salt__['cmd.retcode'](cmd, runas='root') if retrc != 0: raise SaltInvocationError( "make_src_pkg ensuring tree_base \'{0}\' ownership failed with return error \'{1}\', " "check logs for further details".format( tree_base, retrc) ) cmd = "chown {0}:{0} {1}".format(runas, dest_dir) retrc = __salt__['cmd.retcode'](cmd, runas=root_user) if retrc != 0: raise SaltInvocationError( "make_src_pkg ensuring dest_dir \'{0}\' ownership failed with return error \'{1}\', " "check logs for further details".format( dest_dir, retrc) ) spec_pathfile = _get_spec(tree_base, spec, saltenv) # build salt equivalents from scratch if isinstance(sources, six.string_types): sources = sources.split(',') for src in sources: _get_src(tree_base, src, saltenv) # .dsc then assumes sources already build if spec_pathfile.endswith('.dsc'): for efile in os.listdir(tree_base): full = os.path.join(tree_base, efile) trgt = os.path.join(dest_dir, efile) shutil.copy(full, trgt) ret.append(trgt) return ret # obtain name of 'python setup.py sdist' generated tarball, extract the version # and manipulate the name for debian use (convert minix and add '+ds') salttarball = None for afile in os.listdir(tree_base): if afile.startswith('salt-') and afile.endswith('.tar.gz'): salttarball = afile break else: return ret frontname = salttarball.split('.tar.gz') salttar_name = frontname[0] k = salttar_name.rfind('-') debname = salttar_name[:k] + '_' + salttar_name[k+1:] debname += '+ds' debname_orig = debname + '.orig.tar.gz' abspath_debname = os.path.join(tree_base, debname) cmd = 'tar -xvzf {0}'.format(salttarball) retrc = __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user) cmd = 'mv {0} {1}'.format(salttar_name, debname) retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user) cmd = 'tar -cvzf {0} {1}'.format(os.path.join(tree_base, debname_orig), debname) retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user) cmd = 'rm -f {0}'.format(salttarball) retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user, env=env) cmd = 'cp {0} {1}'.format(spec_pathfile, abspath_debname) retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user) cmd = 'tar -xvJf {0}'.format(spec_pathfile) retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user, env=env) cmd = 'rm -f {0}'.format(os.path.basename(spec_pathfile)) retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user) cmd = 'debuild -S -uc -us -sa' retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user, python_shell=True, env=env) cmd = 'rm -fR {0}'.format(abspath_debname) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user) if retrc != 0: raise SaltInvocationError( 'Make source package for destination directory {0}, spec {1}, sources {2}, failed ' 'with return error {3}, check logs for further details'.format( dest_dir, spec, sources, retrc) ) for dfile in os.listdir(tree_base): if not dfile.endswith('.build'): full = os.path.join(tree_base, dfile) trgt = os.path.join(dest_dir, dfile) shutil.copy(full, trgt) ret.append(trgt) return ret
python
def make_src_pkg(dest_dir, spec, sources, env=None, saltenv='base', runas='root'): ''' Create a platform specific source package from the given platform spec/control file and sources CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control.tar.xz https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl SOURCE package and place it in /var/www/html/ on the minion dest_dir Absolute path for directory to write source package spec Absolute path to spec file or equivalent sources Absolute path to source files to build source package from env : None A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'nocheck' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. saltenv: base Salt environment variables runas : root .. versionadded:: fluorine User to create the files and directories .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized. ''' _create_pbuilders(env, runas) tree_base = _mk_tree() ret = [] if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # ensure directories are writable root_user = 'root' retrc = 0 cmd = "chown {0}:{0} {1}".format(runas, tree_base) retrc = __salt__['cmd.retcode'](cmd, runas='root') if retrc != 0: raise SaltInvocationError( "make_src_pkg ensuring tree_base \'{0}\' ownership failed with return error \'{1}\', " "check logs for further details".format( tree_base, retrc) ) cmd = "chown {0}:{0} {1}".format(runas, dest_dir) retrc = __salt__['cmd.retcode'](cmd, runas=root_user) if retrc != 0: raise SaltInvocationError( "make_src_pkg ensuring dest_dir \'{0}\' ownership failed with return error \'{1}\', " "check logs for further details".format( dest_dir, retrc) ) spec_pathfile = _get_spec(tree_base, spec, saltenv) # build salt equivalents from scratch if isinstance(sources, six.string_types): sources = sources.split(',') for src in sources: _get_src(tree_base, src, saltenv) # .dsc then assumes sources already build if spec_pathfile.endswith('.dsc'): for efile in os.listdir(tree_base): full = os.path.join(tree_base, efile) trgt = os.path.join(dest_dir, efile) shutil.copy(full, trgt) ret.append(trgt) return ret # obtain name of 'python setup.py sdist' generated tarball, extract the version # and manipulate the name for debian use (convert minix and add '+ds') salttarball = None for afile in os.listdir(tree_base): if afile.startswith('salt-') and afile.endswith('.tar.gz'): salttarball = afile break else: return ret frontname = salttarball.split('.tar.gz') salttar_name = frontname[0] k = salttar_name.rfind('-') debname = salttar_name[:k] + '_' + salttar_name[k+1:] debname += '+ds' debname_orig = debname + '.orig.tar.gz' abspath_debname = os.path.join(tree_base, debname) cmd = 'tar -xvzf {0}'.format(salttarball) retrc = __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user) cmd = 'mv {0} {1}'.format(salttar_name, debname) retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user) cmd = 'tar -cvzf {0} {1}'.format(os.path.join(tree_base, debname_orig), debname) retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user) cmd = 'rm -f {0}'.format(salttarball) retrc |= __salt__['cmd.retcode'](cmd, cwd=tree_base, runas=root_user, env=env) cmd = 'cp {0} {1}'.format(spec_pathfile, abspath_debname) retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user) cmd = 'tar -xvJf {0}'.format(spec_pathfile) retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user, env=env) cmd = 'rm -f {0}'.format(os.path.basename(spec_pathfile)) retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user) cmd = 'debuild -S -uc -us -sa' retrc |= __salt__['cmd.retcode'](cmd, cwd=abspath_debname, runas=root_user, python_shell=True, env=env) cmd = 'rm -fR {0}'.format(abspath_debname) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user) if retrc != 0: raise SaltInvocationError( 'Make source package for destination directory {0}, spec {1}, sources {2}, failed ' 'with return error {3}, check logs for further details'.format( dest_dir, spec, sources, retrc) ) for dfile in os.listdir(tree_base): if not dfile.endswith('.build'): full = os.path.join(tree_base, dfile) trgt = os.path.join(dest_dir, dfile) shutil.copy(full, trgt) ret.append(trgt) return ret
[ "def", "make_src_pkg", "(", "dest_dir", ",", "spec", ",", "sources", ",", "env", "=", "None", ",", "saltenv", "=", "'base'", ",", "runas", "=", "'root'", ")", ":", "_create_pbuilders", "(", "env", ",", "runas", ")", "tree_base", "=", "_mk_tree", "(", "...
Create a platform specific source package from the given platform spec/control file and sources CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control.tar.xz https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl SOURCE package and place it in /var/www/html/ on the minion dest_dir Absolute path for directory to write source package spec Absolute path to spec file or equivalent sources Absolute path to source files to build source package from env : None A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'nocheck' .. warning:: The above illustrates a common PyYAML pitfall, that **yes**, **no**, **on**, **off**, **true**, and **false** are all loaded as boolean ``True`` and ``False`` values, and must be enclosed in quotes to be used as strings. More info on this (and other) PyYAML idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`. saltenv: base Salt environment variables runas : root .. versionadded:: fluorine User to create the files and directories .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized.
[ "Create", "a", "platform", "specific", "source", "package", "from", "the", "given", "platform", "spec", "/", "control", "file", "and", "sources" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L318-L476
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
build
def build(runas, tgt, dest_dir, spec, sources, deps, env, template, saltenv='base', log_dir='/var/log/salt/pkgbuild'): # pylint: disable=unused-argument ''' Given the package destination directory, the tarball containing debian files (e.g. control) and package sources, use pbuilder to safely build the platform package CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg deb-8-x86_64 /var/www/html https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl package for Debian using pbuilder and place it in /var/www/html/ on the minion ''' ret = {} retrc = 0 try: os.makedirs(dest_dir) except OSError as exc: if exc.errno != errno.EEXIST: raise dsc_dir = tempfile.mkdtemp() try: dscs = make_src_pkg(dsc_dir, spec, sources, env, saltenv, runas) except Exception as exc: shutil.rmtree(dsc_dir) log.error('Failed to make src package, exception \'%s\'', exc) return ret root_user = 'root' #ensure pbuilder setup from runas if other than root if runas != root_user: user_home = os.path.expanduser('~{0}'.format(runas)) root_home = os.path.expanduser('~root') cmd = 'cp {0}/.pbuilderrc {1}/'.format(user_home, root_home) retrc = __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) cmd = 'cp -R {0}/.pbuilder-hooks {1}/'.format(user_home, root_home) retrc = __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) if retrc != 0: raise SaltInvocationError( "build copy pbuilder files from \'{0}\' to \'{1}\' returned error \'{2}\', " "check logs for further details".format(user_home, root_home, retrc)) cmd = '/usr/sbin/pbuilder --create' retrc = __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) if retrc != 0: raise SaltInvocationError( 'pbuilder create failed with return error \'{0}\', ' 'check logs for further details'.format(retrc)) # use default /var/cache/pbuilder/result results_dir = '/var/cache/pbuilder/result' # ensure clean cmd = 'rm -fR {0}'.format(results_dir) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) # dscs should only contain salt orig and debian tarballs and dsc file for dsc in dscs: afile = os.path.basename(dsc) os.path.join(dest_dir, afile) if dsc.endswith('.dsc'): dbase = os.path.dirname(dsc) try: cmd = 'chown {0}:{0} -R {1}'.format(runas, dbase) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) cmd = '/usr/sbin/pbuilder update --override-config' retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) cmd = '/usr/sbin/pbuilder build --debbuildopts "-sa" {0}'.format(dsc) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) if retrc != 0: raise SaltInvocationError( 'pbuilder build or update failed with return error {0}, ' 'check logs for further details'.format(retrc) ) # ignore local deps generated package file for bfile in os.listdir(results_dir): if bfile != 'Packages': full = os.path.join(results_dir, bfile) bdist = os.path.join(dest_dir, bfile) shutil.copy(full, bdist) ret.setdefault('Packages', []).append(bdist) except Exception: log.exception('Error building from %s', dsc) # remove any Packages file created for local dependency processing for pkgzfile in os.listdir(dest_dir): if pkgzfile == 'Packages': pkgzabsfile = os.path.join(dest_dir, pkgzfile) os.remove(pkgzabsfile) cmd = 'chown {0}:{0} -R {1}'.format(runas, dest_dir) __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) shutil.rmtree(dsc_dir) return ret
python
def build(runas, tgt, dest_dir, spec, sources, deps, env, template, saltenv='base', log_dir='/var/log/salt/pkgbuild'): # pylint: disable=unused-argument ''' Given the package destination directory, the tarball containing debian files (e.g. control) and package sources, use pbuilder to safely build the platform package CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg deb-8-x86_64 /var/www/html https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl package for Debian using pbuilder and place it in /var/www/html/ on the minion ''' ret = {} retrc = 0 try: os.makedirs(dest_dir) except OSError as exc: if exc.errno != errno.EEXIST: raise dsc_dir = tempfile.mkdtemp() try: dscs = make_src_pkg(dsc_dir, spec, sources, env, saltenv, runas) except Exception as exc: shutil.rmtree(dsc_dir) log.error('Failed to make src package, exception \'%s\'', exc) return ret root_user = 'root' #ensure pbuilder setup from runas if other than root if runas != root_user: user_home = os.path.expanduser('~{0}'.format(runas)) root_home = os.path.expanduser('~root') cmd = 'cp {0}/.pbuilderrc {1}/'.format(user_home, root_home) retrc = __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) cmd = 'cp -R {0}/.pbuilder-hooks {1}/'.format(user_home, root_home) retrc = __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) if retrc != 0: raise SaltInvocationError( "build copy pbuilder files from \'{0}\' to \'{1}\' returned error \'{2}\', " "check logs for further details".format(user_home, root_home, retrc)) cmd = '/usr/sbin/pbuilder --create' retrc = __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) if retrc != 0: raise SaltInvocationError( 'pbuilder create failed with return error \'{0}\', ' 'check logs for further details'.format(retrc)) # use default /var/cache/pbuilder/result results_dir = '/var/cache/pbuilder/result' # ensure clean cmd = 'rm -fR {0}'.format(results_dir) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) # dscs should only contain salt orig and debian tarballs and dsc file for dsc in dscs: afile = os.path.basename(dsc) os.path.join(dest_dir, afile) if dsc.endswith('.dsc'): dbase = os.path.dirname(dsc) try: cmd = 'chown {0}:{0} -R {1}'.format(runas, dbase) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) cmd = '/usr/sbin/pbuilder update --override-config' retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) cmd = '/usr/sbin/pbuilder build --debbuildopts "-sa" {0}'.format(dsc) retrc |= __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) if retrc != 0: raise SaltInvocationError( 'pbuilder build or update failed with return error {0}, ' 'check logs for further details'.format(retrc) ) # ignore local deps generated package file for bfile in os.listdir(results_dir): if bfile != 'Packages': full = os.path.join(results_dir, bfile) bdist = os.path.join(dest_dir, bfile) shutil.copy(full, bdist) ret.setdefault('Packages', []).append(bdist) except Exception: log.exception('Error building from %s', dsc) # remove any Packages file created for local dependency processing for pkgzfile in os.listdir(dest_dir): if pkgzfile == 'Packages': pkgzabsfile = os.path.join(dest_dir, pkgzfile) os.remove(pkgzabsfile) cmd = 'chown {0}:{0} -R {1}'.format(runas, dest_dir) __salt__['cmd.retcode'](cmd, runas=root_user, python_shell=True, env=env) shutil.rmtree(dsc_dir) return ret
[ "def", "build", "(", "runas", ",", "tgt", ",", "dest_dir", ",", "spec", ",", "sources", ",", "deps", ",", "env", ",", "template", ",", "saltenv", "=", "'base'", ",", "log_dir", "=", "'/var/log/salt/pkgbuild'", ")", ":", "# pylint: disable=unused-argument", "...
Given the package destination directory, the tarball containing debian files (e.g. control) and package sources, use pbuilder to safely build the platform package CLI Example: **Debian** .. code-block:: bash salt '*' pkgbuild.make_src_pkg deb-8-x86_64 /var/www/html https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/deb/python-libnacl.control https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl package for Debian using pbuilder and place it in /var/www/html/ on the minion
[ "Given", "the", "package", "destination", "directory", "the", "tarball", "containing", "debian", "files", "(", "e", ".", "g", ".", "control", ")", "and", "package", "sources", "use", "pbuilder", "to", "safely", "build", "the", "platform", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L479-L591
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
make_repo
def make_repo(repodir, keyid=None, env=None, use_passphrase=False, gnupghome='/etc/salt/gpgkeys', runas='root', timeout=15.0): ''' Make a package repository and optionally sign it and packages present Given the repodir (directory to create repository in), create a Debian repository and optionally sign it and packages present. This state is best used with onchanges linked to your package building states. repodir The directory to find packages that will be in the repository. keyid .. versionchanged:: 2016.3.0 Optional Key ID to use in signing packages and repository. This consists of the last 8 hex digits of the GPG key ID. Utilizes Public and Private keys associated with keyid which have been loaded into the minion's Pillar data. Leverages gpg-agent and gpg-preset-passphrase for caching keys, etc. These pillar values are assumed to be filenames which are present in ``gnupghome``. The pillar keys shown below have to match exactly. For example, contents from a Pillar data file with named Public and Private keys as follows: .. code-block:: yaml gpg_pkg_priv_keyname: gpg_pkg_key.pem gpg_pkg_pub_keyname: gpg_pkg_key.pub env .. versionchanged:: 2016.3.0 A dictionary of environment variables to be utilized in creating the repository. use_passphrase : False .. versionadded:: 2016.3.0 Use a passphrase with the signing key presented in ``keyid``. Passphrase is received from Pillar data which could be passed on the command line with ``pillar`` parameter. For example: .. code-block:: bash pillar='{ "gpg_passphrase" : "my_passphrase" }' gnupghome : /etc/salt/gpgkeys .. versionadded:: 2016.3.0 Location where GPG related files are stored, used with ``keyid``. runas : root .. versionadded:: 2016.3.0 User to create the repository as, and optionally sign packages. .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized. timeout : 15.0 .. versionadded:: 2016.3.4 Timeout in seconds to wait for the prompt for inputting the passphrase. CLI Example: .. code-block:: bash salt '*' pkgbuild.make_repo /var/www/html ''' res = { 'retcode': 1, 'stdout': '', 'stderr': 'initialization value' } retrc = 0 if gnupghome and env is None: env = {} env['GNUPGHOME'] = gnupghome repoconf = os.path.join(repodir, 'conf') if not os.path.isdir(repoconf): os.makedirs(repoconf) codename, repocfg_dists = _get_repo_dists_env(env) repoconfdist = os.path.join(repoconf, 'distributions') with salt.utils.files.fopen(repoconfdist, 'w') as fow: fow.write(salt.utils.stringutils.to_str(repocfg_dists)) repocfg_opts = _get_repo_options_env(env) repoconfopts = os.path.join(repoconf, 'options') with salt.utils.files.fopen(repoconfopts, 'w') as fow: fow.write(salt.utils.stringutils.to_str(repocfg_opts)) cmd = 'chown {0}:{0} -R {1}'.format(runas, repoconf) retrc = __salt__['cmd.retcode'](cmd, runas='root') if retrc != 0: raise SaltInvocationError( 'failed to ensure rights to repoconf directory, error {0}, ' 'check logs for further details'.format(retrc) ) local_keygrip_to_use = None local_key_fingerprint = None local_keyid = None phrase = '' # preset passphase and interaction with gpg-agent gpg_info_file = '{0}/gpg-agent-info-salt'.format(gnupghome) gpg_tty_info_file = '{0}/gpg-tty-info-salt'.format(gnupghome) # if using older than gnupg 2.1, then env file exists older_gnupg = __salt__['file.file_exists'](gpg_info_file) if keyid is not None: with salt.utils.files.fopen(repoconfdist, 'a') as fow: fow.write(salt.utils.stringutils.to_str('SignWith: {0}\n'.format(keyid))) # import_keys pkg_pub_key_file = '{0}/{1}'.format(gnupghome, __salt__['pillar.get']('gpg_pkg_pub_keyname', None)) pkg_priv_key_file = '{0}/{1}'.format(gnupghome, __salt__['pillar.get']('gpg_pkg_priv_keyname', None)) if pkg_pub_key_file is None or pkg_priv_key_file is None: raise SaltInvocationError( 'Pillar data should contain Public and Private keys associated with \'keyid\'' ) try: __salt__['gpg.import_key'](user=runas, filename=pkg_pub_key_file, gnupghome=gnupghome) __salt__['gpg.import_key'](user=runas, filename=pkg_priv_key_file, gnupghome=gnupghome) except SaltInvocationError: raise SaltInvocationError( 'Public and Private key files associated with Pillar data and \'keyid\' ' '{0} could not be found' .format(keyid) ) # gpg keys should have been loaded as part of setup # retrieve specified key, obtain fingerprint and preset passphrase local_keys = __salt__['gpg.list_keys'](user=runas, gnupghome=gnupghome) for gpg_key in local_keys: if keyid == gpg_key['keyid'][8:]: local_keygrip_to_use = gpg_key['fingerprint'] local_key_fingerprint = gpg_key['fingerprint'] local_keyid = gpg_key['keyid'] break if not older_gnupg: try: _check_repo_sign_utils_support('gpg2') cmd = 'gpg2 --with-keygrip --list-secret-keys' except CommandExecutionError: # later gpg versions have dispensed with gpg2 - Ubuntu 18.04 cmd = 'gpg --with-keygrip --list-secret-keys' local_keys2_keygrip = __salt__['cmd.run'](cmd, runas=runas, env=env) local_keys2 = iter(local_keys2_keygrip.splitlines()) try: for line in local_keys2: if line.startswith('sec'): line_fingerprint = next(local_keys2).lstrip().rstrip() if local_key_fingerprint == line_fingerprint: lkeygrip = next(local_keys2).split('=') local_keygrip_to_use = lkeygrip[1].lstrip().rstrip() break except StopIteration: raise SaltInvocationError( 'unable to find keygrip associated with fingerprint \'{0}\' for keyid \'{1}\'' .format(local_key_fingerprint, local_keyid) ) if local_keyid is None: raise SaltInvocationError( 'The key ID \'{0}\' was not found in GnuPG keyring at \'{1}\'' .format(keyid, gnupghome) ) _check_repo_sign_utils_support('debsign') if older_gnupg: with salt.utils.files.fopen(gpg_info_file, 'r') as fow: gpg_raw_info = fow.readlines() for gpg_info_line in gpg_raw_info: gpg_info_line = salt.utils.stringutils.to_unicode(gpg_info_line) gpg_info = gpg_info_line.split('=') env[gpg_info[0]] = gpg_info[1] break else: with salt.utils.files.fopen(gpg_tty_info_file, 'r') as fow: gpg_raw_info = fow.readlines() for gpg_tty_info_line in gpg_raw_info: gpg_tty_info_line = salt.utils.stringutils.to_unicode(gpg_tty_info_line) gpg_tty_info = gpg_tty_info_line.split('=') env[gpg_tty_info[0]] = gpg_tty_info[1] break if use_passphrase: _check_repo_gpg_phrase_utils() phrase = __salt__['pillar.get']('gpg_passphrase') cmd = '/usr/lib/gnupg2/gpg-preset-passphrase --verbose --preset --passphrase "{0}" {1}'.format( phrase, local_keygrip_to_use) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, env=env) for debfile in os.listdir(repodir): abs_file = os.path.join(repodir, debfile) if debfile.endswith('.changes'): os.remove(abs_file) if debfile.endswith('.dsc'): # sign_it_here if older_gnupg: if local_keyid is not None: cmd = 'debsign --re-sign -k {0} {1}'.format(keyid, abs_file) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'.format( codename, abs_file) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) else: # interval of 0.125 is really too fast on some systems interval = 0.5 if local_keyid is not None: number_retries = timeout / interval times_looped = 0 error_msg = 'Failed to debsign file {0}'.format(abs_file) if ((__grains__['os'] in ['Ubuntu'] and __grains__['osmajorrelease'] < 18) or (__grains__['os'] in ['Debian'] and __grains__['osmajorrelease'] <= 8)): cmd = 'debsign --re-sign -k {0} {1}'.format(keyid, abs_file) try: proc = salt.utils.vt.Terminal( cmd, env=env, shell=True, stream_stdout=True, stream_stderr=True ) while proc.has_unread_data: stdout, _ = proc.recv() if stdout and SIGN_PROMPT_RE.search(stdout): # have the prompt for inputting the passphrase proc.sendline(phrase) else: times_looped += 1 if times_looped > number_retries: raise SaltInvocationError( 'Attempting to sign file {0} failed, timed out after {1} seconds'.format( abs_file, int(times_looped * interval)) ) time.sleep(interval) proc_exitstatus = proc.exitstatus if proc_exitstatus != 0: raise SaltInvocationError( 'Signing file {0} failed with proc.status {1}'.format( abs_file, proc_exitstatus) ) except salt.utils.vt.TerminalException as err: trace = traceback.format_exc() log.error(error_msg, err, trace) res = { 'retcode': 1, 'stdout': '', 'stderr': trace} finally: proc.close(terminate=True, kill=True) else: cmd = 'debsign --re-sign -k {0} {1}'.format(local_key_fingerprint, abs_file) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) number_retries = timeout / interval times_looped = 0 error_msg = 'Failed to reprepro includedsc file {0}'.format(abs_file) cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'.format( codename, abs_file) if ((__grains__['os'] in ['Ubuntu'] and __grains__['osmajorrelease'] < 18) or (__grains__['os'] in ['Debian'] and __grains__['osmajorrelease'] <= 8)): try: proc = salt.utils.vt.Terminal( cmd, env=env, shell=True, cwd=repodir, stream_stdout=True, stream_stderr=True ) while proc.has_unread_data: stdout, _ = proc.recv() if stdout and REPREPRO_SIGN_PROMPT_RE.search(stdout): # have the prompt for inputting the passphrase proc.sendline(phrase) else: times_looped += 1 if times_looped > number_retries: raise SaltInvocationError( 'Attempting to reprepro includedsc for file {0} failed, timed out after {1} loops' .format(abs_file, times_looped) ) time.sleep(interval) proc_exitstatus = proc.exitstatus if proc_exitstatus != 0: raise SaltInvocationError( 'Reprepro includedsc for codename {0} and file {1} failed with proc.status {2}'.format( codename, abs_file, proc_exitstatus) ) except salt.utils.vt.TerminalException as err: trace = traceback.format_exc() log.error(error_msg, err, trace) res = { 'retcode': 1, 'stdout': '', 'stderr': trace } finally: proc.close(terminate=True, kill=True) else: retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) if retrc != 0: raise SaltInvocationError( 'Making a repo encountered errors, return error {0}, check logs for further details'.format(retrc)) if debfile.endswith('.deb'): cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedeb {0} {1}'.format( codename, abs_file) res = __salt__['cmd.run_all'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) return res
python
def make_repo(repodir, keyid=None, env=None, use_passphrase=False, gnupghome='/etc/salt/gpgkeys', runas='root', timeout=15.0): ''' Make a package repository and optionally sign it and packages present Given the repodir (directory to create repository in), create a Debian repository and optionally sign it and packages present. This state is best used with onchanges linked to your package building states. repodir The directory to find packages that will be in the repository. keyid .. versionchanged:: 2016.3.0 Optional Key ID to use in signing packages and repository. This consists of the last 8 hex digits of the GPG key ID. Utilizes Public and Private keys associated with keyid which have been loaded into the minion's Pillar data. Leverages gpg-agent and gpg-preset-passphrase for caching keys, etc. These pillar values are assumed to be filenames which are present in ``gnupghome``. The pillar keys shown below have to match exactly. For example, contents from a Pillar data file with named Public and Private keys as follows: .. code-block:: yaml gpg_pkg_priv_keyname: gpg_pkg_key.pem gpg_pkg_pub_keyname: gpg_pkg_key.pub env .. versionchanged:: 2016.3.0 A dictionary of environment variables to be utilized in creating the repository. use_passphrase : False .. versionadded:: 2016.3.0 Use a passphrase with the signing key presented in ``keyid``. Passphrase is received from Pillar data which could be passed on the command line with ``pillar`` parameter. For example: .. code-block:: bash pillar='{ "gpg_passphrase" : "my_passphrase" }' gnupghome : /etc/salt/gpgkeys .. versionadded:: 2016.3.0 Location where GPG related files are stored, used with ``keyid``. runas : root .. versionadded:: 2016.3.0 User to create the repository as, and optionally sign packages. .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized. timeout : 15.0 .. versionadded:: 2016.3.4 Timeout in seconds to wait for the prompt for inputting the passphrase. CLI Example: .. code-block:: bash salt '*' pkgbuild.make_repo /var/www/html ''' res = { 'retcode': 1, 'stdout': '', 'stderr': 'initialization value' } retrc = 0 if gnupghome and env is None: env = {} env['GNUPGHOME'] = gnupghome repoconf = os.path.join(repodir, 'conf') if not os.path.isdir(repoconf): os.makedirs(repoconf) codename, repocfg_dists = _get_repo_dists_env(env) repoconfdist = os.path.join(repoconf, 'distributions') with salt.utils.files.fopen(repoconfdist, 'w') as fow: fow.write(salt.utils.stringutils.to_str(repocfg_dists)) repocfg_opts = _get_repo_options_env(env) repoconfopts = os.path.join(repoconf, 'options') with salt.utils.files.fopen(repoconfopts, 'w') as fow: fow.write(salt.utils.stringutils.to_str(repocfg_opts)) cmd = 'chown {0}:{0} -R {1}'.format(runas, repoconf) retrc = __salt__['cmd.retcode'](cmd, runas='root') if retrc != 0: raise SaltInvocationError( 'failed to ensure rights to repoconf directory, error {0}, ' 'check logs for further details'.format(retrc) ) local_keygrip_to_use = None local_key_fingerprint = None local_keyid = None phrase = '' # preset passphase and interaction with gpg-agent gpg_info_file = '{0}/gpg-agent-info-salt'.format(gnupghome) gpg_tty_info_file = '{0}/gpg-tty-info-salt'.format(gnupghome) # if using older than gnupg 2.1, then env file exists older_gnupg = __salt__['file.file_exists'](gpg_info_file) if keyid is not None: with salt.utils.files.fopen(repoconfdist, 'a') as fow: fow.write(salt.utils.stringutils.to_str('SignWith: {0}\n'.format(keyid))) # import_keys pkg_pub_key_file = '{0}/{1}'.format(gnupghome, __salt__['pillar.get']('gpg_pkg_pub_keyname', None)) pkg_priv_key_file = '{0}/{1}'.format(gnupghome, __salt__['pillar.get']('gpg_pkg_priv_keyname', None)) if pkg_pub_key_file is None or pkg_priv_key_file is None: raise SaltInvocationError( 'Pillar data should contain Public and Private keys associated with \'keyid\'' ) try: __salt__['gpg.import_key'](user=runas, filename=pkg_pub_key_file, gnupghome=gnupghome) __salt__['gpg.import_key'](user=runas, filename=pkg_priv_key_file, gnupghome=gnupghome) except SaltInvocationError: raise SaltInvocationError( 'Public and Private key files associated with Pillar data and \'keyid\' ' '{0} could not be found' .format(keyid) ) # gpg keys should have been loaded as part of setup # retrieve specified key, obtain fingerprint and preset passphrase local_keys = __salt__['gpg.list_keys'](user=runas, gnupghome=gnupghome) for gpg_key in local_keys: if keyid == gpg_key['keyid'][8:]: local_keygrip_to_use = gpg_key['fingerprint'] local_key_fingerprint = gpg_key['fingerprint'] local_keyid = gpg_key['keyid'] break if not older_gnupg: try: _check_repo_sign_utils_support('gpg2') cmd = 'gpg2 --with-keygrip --list-secret-keys' except CommandExecutionError: # later gpg versions have dispensed with gpg2 - Ubuntu 18.04 cmd = 'gpg --with-keygrip --list-secret-keys' local_keys2_keygrip = __salt__['cmd.run'](cmd, runas=runas, env=env) local_keys2 = iter(local_keys2_keygrip.splitlines()) try: for line in local_keys2: if line.startswith('sec'): line_fingerprint = next(local_keys2).lstrip().rstrip() if local_key_fingerprint == line_fingerprint: lkeygrip = next(local_keys2).split('=') local_keygrip_to_use = lkeygrip[1].lstrip().rstrip() break except StopIteration: raise SaltInvocationError( 'unable to find keygrip associated with fingerprint \'{0}\' for keyid \'{1}\'' .format(local_key_fingerprint, local_keyid) ) if local_keyid is None: raise SaltInvocationError( 'The key ID \'{0}\' was not found in GnuPG keyring at \'{1}\'' .format(keyid, gnupghome) ) _check_repo_sign_utils_support('debsign') if older_gnupg: with salt.utils.files.fopen(gpg_info_file, 'r') as fow: gpg_raw_info = fow.readlines() for gpg_info_line in gpg_raw_info: gpg_info_line = salt.utils.stringutils.to_unicode(gpg_info_line) gpg_info = gpg_info_line.split('=') env[gpg_info[0]] = gpg_info[1] break else: with salt.utils.files.fopen(gpg_tty_info_file, 'r') as fow: gpg_raw_info = fow.readlines() for gpg_tty_info_line in gpg_raw_info: gpg_tty_info_line = salt.utils.stringutils.to_unicode(gpg_tty_info_line) gpg_tty_info = gpg_tty_info_line.split('=') env[gpg_tty_info[0]] = gpg_tty_info[1] break if use_passphrase: _check_repo_gpg_phrase_utils() phrase = __salt__['pillar.get']('gpg_passphrase') cmd = '/usr/lib/gnupg2/gpg-preset-passphrase --verbose --preset --passphrase "{0}" {1}'.format( phrase, local_keygrip_to_use) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, env=env) for debfile in os.listdir(repodir): abs_file = os.path.join(repodir, debfile) if debfile.endswith('.changes'): os.remove(abs_file) if debfile.endswith('.dsc'): # sign_it_here if older_gnupg: if local_keyid is not None: cmd = 'debsign --re-sign -k {0} {1}'.format(keyid, abs_file) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'.format( codename, abs_file) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) else: # interval of 0.125 is really too fast on some systems interval = 0.5 if local_keyid is not None: number_retries = timeout / interval times_looped = 0 error_msg = 'Failed to debsign file {0}'.format(abs_file) if ((__grains__['os'] in ['Ubuntu'] and __grains__['osmajorrelease'] < 18) or (__grains__['os'] in ['Debian'] and __grains__['osmajorrelease'] <= 8)): cmd = 'debsign --re-sign -k {0} {1}'.format(keyid, abs_file) try: proc = salt.utils.vt.Terminal( cmd, env=env, shell=True, stream_stdout=True, stream_stderr=True ) while proc.has_unread_data: stdout, _ = proc.recv() if stdout and SIGN_PROMPT_RE.search(stdout): # have the prompt for inputting the passphrase proc.sendline(phrase) else: times_looped += 1 if times_looped > number_retries: raise SaltInvocationError( 'Attempting to sign file {0} failed, timed out after {1} seconds'.format( abs_file, int(times_looped * interval)) ) time.sleep(interval) proc_exitstatus = proc.exitstatus if proc_exitstatus != 0: raise SaltInvocationError( 'Signing file {0} failed with proc.status {1}'.format( abs_file, proc_exitstatus) ) except salt.utils.vt.TerminalException as err: trace = traceback.format_exc() log.error(error_msg, err, trace) res = { 'retcode': 1, 'stdout': '', 'stderr': trace} finally: proc.close(terminate=True, kill=True) else: cmd = 'debsign --re-sign -k {0} {1}'.format(local_key_fingerprint, abs_file) retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) number_retries = timeout / interval times_looped = 0 error_msg = 'Failed to reprepro includedsc file {0}'.format(abs_file) cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'.format( codename, abs_file) if ((__grains__['os'] in ['Ubuntu'] and __grains__['osmajorrelease'] < 18) or (__grains__['os'] in ['Debian'] and __grains__['osmajorrelease'] <= 8)): try: proc = salt.utils.vt.Terminal( cmd, env=env, shell=True, cwd=repodir, stream_stdout=True, stream_stderr=True ) while proc.has_unread_data: stdout, _ = proc.recv() if stdout and REPREPRO_SIGN_PROMPT_RE.search(stdout): # have the prompt for inputting the passphrase proc.sendline(phrase) else: times_looped += 1 if times_looped > number_retries: raise SaltInvocationError( 'Attempting to reprepro includedsc for file {0} failed, timed out after {1} loops' .format(abs_file, times_looped) ) time.sleep(interval) proc_exitstatus = proc.exitstatus if proc_exitstatus != 0: raise SaltInvocationError( 'Reprepro includedsc for codename {0} and file {1} failed with proc.status {2}'.format( codename, abs_file, proc_exitstatus) ) except salt.utils.vt.TerminalException as err: trace = traceback.format_exc() log.error(error_msg, err, trace) res = { 'retcode': 1, 'stdout': '', 'stderr': trace } finally: proc.close(terminate=True, kill=True) else: retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) if retrc != 0: raise SaltInvocationError( 'Making a repo encountered errors, return error {0}, check logs for further details'.format(retrc)) if debfile.endswith('.deb'): cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedeb {0} {1}'.format( codename, abs_file) res = __salt__['cmd.run_all'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) return res
[ "def", "make_repo", "(", "repodir", ",", "keyid", "=", "None", ",", "env", "=", "None", ",", "use_passphrase", "=", "False", ",", "gnupghome", "=", "'/etc/salt/gpgkeys'", ",", "runas", "=", "'root'", ",", "timeout", "=", "15.0", ")", ":", "res", "=", "...
Make a package repository and optionally sign it and packages present Given the repodir (directory to create repository in), create a Debian repository and optionally sign it and packages present. This state is best used with onchanges linked to your package building states. repodir The directory to find packages that will be in the repository. keyid .. versionchanged:: 2016.3.0 Optional Key ID to use in signing packages and repository. This consists of the last 8 hex digits of the GPG key ID. Utilizes Public and Private keys associated with keyid which have been loaded into the minion's Pillar data. Leverages gpg-agent and gpg-preset-passphrase for caching keys, etc. These pillar values are assumed to be filenames which are present in ``gnupghome``. The pillar keys shown below have to match exactly. For example, contents from a Pillar data file with named Public and Private keys as follows: .. code-block:: yaml gpg_pkg_priv_keyname: gpg_pkg_key.pem gpg_pkg_pub_keyname: gpg_pkg_key.pub env .. versionchanged:: 2016.3.0 A dictionary of environment variables to be utilized in creating the repository. use_passphrase : False .. versionadded:: 2016.3.0 Use a passphrase with the signing key presented in ``keyid``. Passphrase is received from Pillar data which could be passed on the command line with ``pillar`` parameter. For example: .. code-block:: bash pillar='{ "gpg_passphrase" : "my_passphrase" }' gnupghome : /etc/salt/gpgkeys .. versionadded:: 2016.3.0 Location where GPG related files are stored, used with ``keyid``. runas : root .. versionadded:: 2016.3.0 User to create the repository as, and optionally sign packages. .. note:: Ensure the user has correct permissions to any files and directories which are to be utilized. timeout : 15.0 .. versionadded:: 2016.3.4 Timeout in seconds to wait for the prompt for inputting the passphrase. CLI Example: .. code-block:: bash salt '*' pkgbuild.make_repo /var/www/html
[ "Make", "a", "package", "repository", "and", "optionally", "sign", "it", "and", "packages", "present" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L594-L945
train
saltstack/salt
salt/runners/vault.py
generate_token
def generate_token(minion_id, signature, impersonated_by_master=False): ''' Generate a Vault token for minion minion_id minion_id The id of the minion that requests a token signature Cryptographic signature which validates that the request is indeed sent by the minion (or the master, see impersonated_by_master). impersonated_by_master If the master needs to create a token on behalf of the minion, this is True. This happens when the master generates minion pillars. ''' log.debug( 'Token generation request for %s (impersonated by master: %s)', minion_id, impersonated_by_master ) _validate_signature(minion_id, signature, impersonated_by_master) try: config = __opts__['vault'] verify = config.get('verify', None) if config['auth']['method'] == 'approle': if _selftoken_expired(): log.debug('Vault token expired. Recreating one') # Requesting a short ttl token url = '{0}/v1/auth/approle/login'.format(config['url']) payload = {'role_id': config['auth']['role_id']} if 'secret_id' in config['auth']: payload['secret_id'] = config['auth']['secret_id'] response = requests.post(url, json=payload, verify=verify) if response.status_code != 200: return {'error': response.reason} config['auth']['token'] = response.json()['auth']['client_token'] url = _get_token_create_url(config) headers = {'X-Vault-Token': config['auth']['token']} audit_data = { 'saltstack-jid': globals().get('__jid__', '<no jid set>'), 'saltstack-minion': minion_id, 'saltstack-user': globals().get('__user__', '<no user set>') } payload = { 'policies': _get_policies(minion_id, config), 'num_uses': 1, 'meta': audit_data } if payload['policies'] == []: return {'error': 'No policies matched minion'} log.trace('Sending token creation request to Vault') response = requests.post(url, headers=headers, json=payload, verify=verify) if response.status_code != 200: return {'error': response.reason} auth_data = response.json()['auth'] return { 'token': auth_data['client_token'], 'url': config['url'], 'verify': verify, } except Exception as e: return {'error': six.text_type(e)}
python
def generate_token(minion_id, signature, impersonated_by_master=False): ''' Generate a Vault token for minion minion_id minion_id The id of the minion that requests a token signature Cryptographic signature which validates that the request is indeed sent by the minion (or the master, see impersonated_by_master). impersonated_by_master If the master needs to create a token on behalf of the minion, this is True. This happens when the master generates minion pillars. ''' log.debug( 'Token generation request for %s (impersonated by master: %s)', minion_id, impersonated_by_master ) _validate_signature(minion_id, signature, impersonated_by_master) try: config = __opts__['vault'] verify = config.get('verify', None) if config['auth']['method'] == 'approle': if _selftoken_expired(): log.debug('Vault token expired. Recreating one') # Requesting a short ttl token url = '{0}/v1/auth/approle/login'.format(config['url']) payload = {'role_id': config['auth']['role_id']} if 'secret_id' in config['auth']: payload['secret_id'] = config['auth']['secret_id'] response = requests.post(url, json=payload, verify=verify) if response.status_code != 200: return {'error': response.reason} config['auth']['token'] = response.json()['auth']['client_token'] url = _get_token_create_url(config) headers = {'X-Vault-Token': config['auth']['token']} audit_data = { 'saltstack-jid': globals().get('__jid__', '<no jid set>'), 'saltstack-minion': minion_id, 'saltstack-user': globals().get('__user__', '<no user set>') } payload = { 'policies': _get_policies(minion_id, config), 'num_uses': 1, 'meta': audit_data } if payload['policies'] == []: return {'error': 'No policies matched minion'} log.trace('Sending token creation request to Vault') response = requests.post(url, headers=headers, json=payload, verify=verify) if response.status_code != 200: return {'error': response.reason} auth_data = response.json()['auth'] return { 'token': auth_data['client_token'], 'url': config['url'], 'verify': verify, } except Exception as e: return {'error': six.text_type(e)}
[ "def", "generate_token", "(", "minion_id", ",", "signature", ",", "impersonated_by_master", "=", "False", ")", ":", "log", ".", "debug", "(", "'Token generation request for %s (impersonated by master: %s)'", ",", "minion_id", ",", "impersonated_by_master", ")", "_validate...
Generate a Vault token for minion minion_id minion_id The id of the minion that requests a token signature Cryptographic signature which validates that the request is indeed sent by the minion (or the master, see impersonated_by_master). impersonated_by_master If the master needs to create a token on behalf of the minion, this is True. This happens when the master generates minion pillars.
[ "Generate", "a", "Vault", "token", "for", "minion", "minion_id" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L28-L96
train
saltstack/salt
salt/runners/vault.py
unseal
def unseal(): ''' Unseal Vault server This function uses the 'keys' from the 'vault' configuration to unseal vault server vault: keys: - n63/TbrQuL3xaIW7ZZpuXj/tIfnK1/MbVxO4vT3wYD2A - S9OwCvMRhErEA4NVVELYBs6w/Me6+urgUr24xGK44Uy3 - F1j4b7JKq850NS6Kboiy5laJ0xY8dWJvB3fcwA+SraYl - 1cYtvjKJNDVam9c7HNqJUfINk4PYyAXIpjkpN/sIuzPv - 3pPK5X6vGtwLhNOFv1U2elahECz3HpRUfNXJFYLw6lid .. note: This function will send unsealed keys until the api returns back that the vault has been unsealed CLI Examples: .. code-block:: bash salt-run vault.unseal ''' for key in __opts__['vault']['keys']: ret = __utils__['vault.make_request']('PUT', 'v1/sys/unseal', data=json.dumps({'key': key})).json() if ret['sealed'] is False: return True return False
python
def unseal(): ''' Unseal Vault server This function uses the 'keys' from the 'vault' configuration to unseal vault server vault: keys: - n63/TbrQuL3xaIW7ZZpuXj/tIfnK1/MbVxO4vT3wYD2A - S9OwCvMRhErEA4NVVELYBs6w/Me6+urgUr24xGK44Uy3 - F1j4b7JKq850NS6Kboiy5laJ0xY8dWJvB3fcwA+SraYl - 1cYtvjKJNDVam9c7HNqJUfINk4PYyAXIpjkpN/sIuzPv - 3pPK5X6vGtwLhNOFv1U2elahECz3HpRUfNXJFYLw6lid .. note: This function will send unsealed keys until the api returns back that the vault has been unsealed CLI Examples: .. code-block:: bash salt-run vault.unseal ''' for key in __opts__['vault']['keys']: ret = __utils__['vault.make_request']('PUT', 'v1/sys/unseal', data=json.dumps({'key': key})).json() if ret['sealed'] is False: return True return False
[ "def", "unseal", "(", ")", ":", "for", "key", "in", "__opts__", "[", "'vault'", "]", "[", "'keys'", "]", ":", "ret", "=", "__utils__", "[", "'vault.make_request'", "]", "(", "'PUT'", ",", "'v1/sys/unseal'", ",", "data", "=", "json", ".", "dumps", "(", ...
Unseal Vault server This function uses the 'keys' from the 'vault' configuration to unseal vault server vault: keys: - n63/TbrQuL3xaIW7ZZpuXj/tIfnK1/MbVxO4vT3wYD2A - S9OwCvMRhErEA4NVVELYBs6w/Me6+urgUr24xGK44Uy3 - F1j4b7JKq850NS6Kboiy5laJ0xY8dWJvB3fcwA+SraYl - 1cYtvjKJNDVam9c7HNqJUfINk4PYyAXIpjkpN/sIuzPv - 3pPK5X6vGtwLhNOFv1U2elahECz3HpRUfNXJFYLw6lid .. note: This function will send unsealed keys until the api returns back that the vault has been unsealed CLI Examples: .. code-block:: bash salt-run vault.unseal
[ "Unseal", "Vault", "server" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L99-L126
train
saltstack/salt
salt/runners/vault.py
_validate_signature
def _validate_signature(minion_id, signature, impersonated_by_master): ''' Validate that either minion with id minion_id, or the master, signed the request ''' pki_dir = __opts__['pki_dir'] if impersonated_by_master: public_key = '{0}/master.pub'.format(pki_dir) else: public_key = '{0}/minions/{1}'.format(pki_dir, minion_id) log.trace('Validating signature for %s', minion_id) signature = base64.b64decode(signature) if not salt.crypt.verify_signature(public_key, minion_id, signature): raise salt.exceptions.AuthenticationError( 'Could not validate token request from {0}'.format(minion_id) ) log.trace('Signature ok')
python
def _validate_signature(minion_id, signature, impersonated_by_master): ''' Validate that either minion with id minion_id, or the master, signed the request ''' pki_dir = __opts__['pki_dir'] if impersonated_by_master: public_key = '{0}/master.pub'.format(pki_dir) else: public_key = '{0}/minions/{1}'.format(pki_dir, minion_id) log.trace('Validating signature for %s', minion_id) signature = base64.b64decode(signature) if not salt.crypt.verify_signature(public_key, minion_id, signature): raise salt.exceptions.AuthenticationError( 'Could not validate token request from {0}'.format(minion_id) ) log.trace('Signature ok')
[ "def", "_validate_signature", "(", "minion_id", ",", "signature", ",", "impersonated_by_master", ")", ":", "pki_dir", "=", "__opts__", "[", "'pki_dir'", "]", "if", "impersonated_by_master", ":", "public_key", "=", "'{0}/master.pub'", ".", "format", "(", "pki_dir", ...
Validate that either minion with id minion_id, or the master, signed the request
[ "Validate", "that", "either", "minion", "with", "id", "minion_id", "or", "the", "master", "signed", "the", "request" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L146-L163
train
saltstack/salt
salt/runners/vault.py
_get_policies
def _get_policies(minion_id, config): ''' Get the policies that should be applied to a token for minion_id ''' _, grains, _ = salt.utils.minions.get_minion_data(minion_id, __opts__) policy_patterns = config.get( 'policies', ['saltstack/minion/{minion}', 'saltstack/minions'] ) mappings = {'minion': minion_id, 'grains': grains or {}} policies = [] for pattern in policy_patterns: try: for expanded_pattern in _expand_pattern_lists(pattern, **mappings): policies.append( expanded_pattern.format(**mappings) .lower() # Vault requirement ) except KeyError: log.warning('Could not resolve policy pattern %s', pattern) log.debug('%s policies: %s', minion_id, policies) return policies
python
def _get_policies(minion_id, config): ''' Get the policies that should be applied to a token for minion_id ''' _, grains, _ = salt.utils.minions.get_minion_data(minion_id, __opts__) policy_patterns = config.get( 'policies', ['saltstack/minion/{minion}', 'saltstack/minions'] ) mappings = {'minion': minion_id, 'grains': grains or {}} policies = [] for pattern in policy_patterns: try: for expanded_pattern in _expand_pattern_lists(pattern, **mappings): policies.append( expanded_pattern.format(**mappings) .lower() # Vault requirement ) except KeyError: log.warning('Could not resolve policy pattern %s', pattern) log.debug('%s policies: %s', minion_id, policies) return policies
[ "def", "_get_policies", "(", "minion_id", ",", "config", ")", ":", "_", ",", "grains", ",", "_", "=", "salt", ".", "utils", ".", "minions", ".", "get_minion_data", "(", "minion_id", ",", "__opts__", ")", "policy_patterns", "=", "config", ".", "get", "(",...
Get the policies that should be applied to a token for minion_id
[ "Get", "the", "policies", "that", "should", "be", "applied", "to", "a", "token", "for", "minion_id" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L166-L189
train
saltstack/salt
salt/runners/vault.py
_expand_pattern_lists
def _expand_pattern_lists(pattern, **mappings): ''' Expands the pattern for any list-valued mappings, such that for any list of length N in the mappings present in the pattern, N copies of the pattern are returned, each with an element of the list substituted. pattern: A pattern to expand, for example ``by-role/{grains[roles]}`` mappings: A dictionary of variables that can be expanded into the pattern. Example: Given the pattern `` by-role/{grains[roles]}`` and the below grains .. code-block:: yaml grains: roles: - web - database This function will expand into two patterns, ``[by-role/web, by-role/database]``. Note that this method does not expand any non-list patterns. ''' expanded_patterns = [] f = string.Formatter() ''' This function uses a string.Formatter to get all the formatting tokens from the pattern, then recursively replaces tokens whose expanded value is a list. For a list with N items, it will create N new pattern strings and then continue with the next token. In practice this is expected to not be very expensive, since patterns will typically involve a handful of lists at most. ''' # pylint: disable=W0105 for (_, field_name, _, _) in f.parse(pattern): if field_name is None: continue (value, _) = f.get_field(field_name, None, mappings) if isinstance(value, list): token = '{{{0}}}'.format(field_name) expanded = [pattern.replace(token, six.text_type(elem)) for elem in value] for expanded_item in expanded: result = _expand_pattern_lists(expanded_item, **mappings) expanded_patterns += result return expanded_patterns return [pattern]
python
def _expand_pattern_lists(pattern, **mappings): ''' Expands the pattern for any list-valued mappings, such that for any list of length N in the mappings present in the pattern, N copies of the pattern are returned, each with an element of the list substituted. pattern: A pattern to expand, for example ``by-role/{grains[roles]}`` mappings: A dictionary of variables that can be expanded into the pattern. Example: Given the pattern `` by-role/{grains[roles]}`` and the below grains .. code-block:: yaml grains: roles: - web - database This function will expand into two patterns, ``[by-role/web, by-role/database]``. Note that this method does not expand any non-list patterns. ''' expanded_patterns = [] f = string.Formatter() ''' This function uses a string.Formatter to get all the formatting tokens from the pattern, then recursively replaces tokens whose expanded value is a list. For a list with N items, it will create N new pattern strings and then continue with the next token. In practice this is expected to not be very expensive, since patterns will typically involve a handful of lists at most. ''' # pylint: disable=W0105 for (_, field_name, _, _) in f.parse(pattern): if field_name is None: continue (value, _) = f.get_field(field_name, None, mappings) if isinstance(value, list): token = '{{{0}}}'.format(field_name) expanded = [pattern.replace(token, six.text_type(elem)) for elem in value] for expanded_item in expanded: result = _expand_pattern_lists(expanded_item, **mappings) expanded_patterns += result return expanded_patterns return [pattern]
[ "def", "_expand_pattern_lists", "(", "pattern", ",", "*", "*", "mappings", ")", ":", "expanded_patterns", "=", "[", "]", "f", "=", "string", ".", "Formatter", "(", ")", "'''\n This function uses a string.Formatter to get all the formatting tokens from\n the pattern, t...
Expands the pattern for any list-valued mappings, such that for any list of length N in the mappings present in the pattern, N copies of the pattern are returned, each with an element of the list substituted. pattern: A pattern to expand, for example ``by-role/{grains[roles]}`` mappings: A dictionary of variables that can be expanded into the pattern. Example: Given the pattern `` by-role/{grains[roles]}`` and the below grains .. code-block:: yaml grains: roles: - web - database This function will expand into two patterns, ``[by-role/web, by-role/database]``. Note that this method does not expand any non-list patterns.
[ "Expands", "the", "pattern", "for", "any", "list", "-", "valued", "mappings", "such", "that", "for", "any", "list", "of", "length", "N", "in", "the", "mappings", "present", "in", "the", "pattern", "N", "copies", "of", "the", "pattern", "are", "returned", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L192-L239
train
saltstack/salt
salt/runners/vault.py
_selftoken_expired
def _selftoken_expired(): ''' Validate the current token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/auth/token/lookup-self'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return True headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.get(url, headers=headers, verify=verify) if response.status_code != 200: return True return False except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up self token : {0}'.format(six.text_type(e)) )
python
def _selftoken_expired(): ''' Validate the current token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/auth/token/lookup-self'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return True headers = {'X-Vault-Token': __opts__['vault']['auth']['token']} response = requests.get(url, headers=headers, verify=verify) if response.status_code != 200: return True return False except Exception as e: raise salt.exceptions.CommandExecutionError( 'Error while looking up self token : {0}'.format(six.text_type(e)) )
[ "def", "_selftoken_expired", "(", ")", ":", "try", ":", "verify", "=", "__opts__", "[", "'vault'", "]", ".", "get", "(", "'verify'", ",", "None", ")", "url", "=", "'{0}/v1/auth/token/lookup-self'", ".", "format", "(", "__opts__", "[", "'vault'", "]", "[", ...
Validate the current token exists and is still valid
[ "Validate", "the", "current", "token", "exists", "and", "is", "still", "valid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L242-L259
train
saltstack/salt
salt/runners/vault.py
_get_token_create_url
def _get_token_create_url(config): ''' Create Vault url for token creation ''' role_name = config.get('role_name', None) auth_path = '/v1/auth/token/create' base_url = config['url'] return '/'.join(x.strip('/') for x in (base_url, auth_path, role_name) if x)
python
def _get_token_create_url(config): ''' Create Vault url for token creation ''' role_name = config.get('role_name', None) auth_path = '/v1/auth/token/create' base_url = config['url'] return '/'.join(x.strip('/') for x in (base_url, auth_path, role_name) if x)
[ "def", "_get_token_create_url", "(", "config", ")", ":", "role_name", "=", "config", ".", "get", "(", "'role_name'", ",", "None", ")", "auth_path", "=", "'/v1/auth/token/create'", "base_url", "=", "config", "[", "'url'", "]", "return", "'/'", ".", "join", "(...
Create Vault url for token creation
[ "Create", "Vault", "url", "for", "token", "creation" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L262-L269
train
saltstack/salt
salt/modules/boto_lambda.py
_find_function
def _find_function(name, region=None, key=None, keyid=None, profile=None): ''' Given function name, find and return matching Lambda information. ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for funcs in __utils__['boto3.paged_call'](conn.list_functions): for func in funcs['Functions']: if func['FunctionName'] == name: return func return None
python
def _find_function(name, region=None, key=None, keyid=None, profile=None): ''' Given function name, find and return matching Lambda information. ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for funcs in __utils__['boto3.paged_call'](conn.list_functions): for func in funcs['Functions']: if func['FunctionName'] == name: return func return None
[ "def", "_find_function", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid...
Given function name, find and return matching Lambda information.
[ "Given", "function", "name", "find", "and", "return", "matching", "Lambda", "information", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L138-L149
train
saltstack/salt
salt/modules/boto_lambda.py
function_exists
def function_exists(FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given a function name, check to see if the given function name exists. Returns True if the given function exists and returns False if the given function does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.function_exists myfunction ''' try: func = _find_function(FunctionName, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(func)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def function_exists(FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given a function name, check to see if the given function name exists. Returns True if the given function exists and returns False if the given function does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.function_exists myfunction ''' try: func = _find_function(FunctionName, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(func)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "function_exists", "(", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "func", "=", "_find_function", "(", "FunctionName", ",", "region", "=", "r...
Given a function name, check to see if the given function name exists. Returns True if the given function exists and returns False if the given function does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.function_exists myfunction
[ "Given", "a", "function", "name", "check", "to", "see", "if", "the", "given", "function", "name", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L152-L173
train
saltstack/salt
salt/modules/boto_lambda.py
create_function
def create_function(FunctionName, Runtime, Role, Handler, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Description="", Timeout=3, MemorySize=128, Publish=False, WaitForRole=False, RoleRetries=5, region=None, key=None, keyid=None, profile=None, VpcConfig=None, Environment=None): ''' .. versionadded:: 2017.7.0 Given a valid config, create a function. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } Returns ``{'created': True}`` if the function was created and ``{created: False}`` if the function was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_function my_function python2.7 my_role my_file.my_function my_function.zip salt myminion boto_lamba.create_function my_function python2.7 my_role my_file.my_function salt://files/my_function.zip ''' role_arn = _get_role_arn(Role, region=region, key=key, keyid=keyid, profile=profile) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if ZipFile: if S3Bucket or S3Key or S3ObjectVersion: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') if '://' in ZipFile: # Looks like a remote URL to me... dlZipFile = __salt__['cp.cache_file'](path=ZipFile) if dlZipFile is False: ret['result'] = False ret['comment'] = 'Failed to cache ZipFile `{0}`.'.format(ZipFile) return ret ZipFile = dlZipFile code = { 'ZipFile': _filedata(ZipFile), } else: if not S3Bucket or not S3Key: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') code = { 'S3Bucket': S3Bucket, 'S3Key': S3Key, } if S3ObjectVersion: code['S3ObjectVersion'] = S3ObjectVersion kwargs = {} if VpcConfig is not None: kwargs['VpcConfig'] = _resolve_vpcconfig(VpcConfig, region=region, key=key, keyid=keyid, profile=profile) if Environment is not None: kwargs['Environment'] = Environment if WaitForRole: retrycount = RoleRetries else: retrycount = 1 for retry in range(retrycount, 0, -1): try: func = conn.create_function(FunctionName=FunctionName, Runtime=Runtime, Role=role_arn, Handler=Handler, Code=code, Description=Description, Timeout=Timeout, MemorySize=MemorySize, Publish=Publish, **kwargs) except ClientError as e: if retry > 1 and e.response.get('Error', {}).get('Code') == 'InvalidParameterValueException': log.info( 'Function not created but IAM role may not have propagated, will retry') # exponential backoff time.sleep((2 ** (RoleRetries - retry)) + (random.randint(0, 1000) / 1000)) continue else: raise else: break if func: log.info('The newly created function name is %s', func['FunctionName']) return {'created': True, 'name': func['FunctionName']} else: log.warning('Function was not created') return {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_function(FunctionName, Runtime, Role, Handler, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Description="", Timeout=3, MemorySize=128, Publish=False, WaitForRole=False, RoleRetries=5, region=None, key=None, keyid=None, profile=None, VpcConfig=None, Environment=None): ''' .. versionadded:: 2017.7.0 Given a valid config, create a function. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } Returns ``{'created': True}`` if the function was created and ``{created: False}`` if the function was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_function my_function python2.7 my_role my_file.my_function my_function.zip salt myminion boto_lamba.create_function my_function python2.7 my_role my_file.my_function salt://files/my_function.zip ''' role_arn = _get_role_arn(Role, region=region, key=key, keyid=keyid, profile=profile) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if ZipFile: if S3Bucket or S3Key or S3ObjectVersion: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') if '://' in ZipFile: # Looks like a remote URL to me... dlZipFile = __salt__['cp.cache_file'](path=ZipFile) if dlZipFile is False: ret['result'] = False ret['comment'] = 'Failed to cache ZipFile `{0}`.'.format(ZipFile) return ret ZipFile = dlZipFile code = { 'ZipFile': _filedata(ZipFile), } else: if not S3Bucket or not S3Key: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') code = { 'S3Bucket': S3Bucket, 'S3Key': S3Key, } if S3ObjectVersion: code['S3ObjectVersion'] = S3ObjectVersion kwargs = {} if VpcConfig is not None: kwargs['VpcConfig'] = _resolve_vpcconfig(VpcConfig, region=region, key=key, keyid=keyid, profile=profile) if Environment is not None: kwargs['Environment'] = Environment if WaitForRole: retrycount = RoleRetries else: retrycount = 1 for retry in range(retrycount, 0, -1): try: func = conn.create_function(FunctionName=FunctionName, Runtime=Runtime, Role=role_arn, Handler=Handler, Code=code, Description=Description, Timeout=Timeout, MemorySize=MemorySize, Publish=Publish, **kwargs) except ClientError as e: if retry > 1 and e.response.get('Error', {}).get('Code') == 'InvalidParameterValueException': log.info( 'Function not created but IAM role may not have propagated, will retry') # exponential backoff time.sleep((2 ** (RoleRetries - retry)) + (random.randint(0, 1000) / 1000)) continue else: raise else: break if func: log.info('The newly created function name is %s', func['FunctionName']) return {'created': True, 'name': func['FunctionName']} else: log.warning('Function was not created') return {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_function", "(", "FunctionName", ",", "Runtime", ",", "Role", ",", "Handler", ",", "ZipFile", "=", "None", ",", "S3Bucket", "=", "None", ",", "S3Key", "=", "None", ",", "S3ObjectVersion", "=", "None", ",", "Description", "=", "\"\"", ",", "...
.. versionadded:: 2017.7.0 Given a valid config, create a function. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } Returns ``{'created': True}`` if the function was created and ``{created: False}`` if the function was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_function my_function python2.7 my_role my_file.my_function my_function.zip salt myminion boto_lamba.create_function my_function python2.7 my_role my_file.my_function salt://files/my_function.zip
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L211-L308
train
saltstack/salt
salt/modules/boto_lambda.py
delete_function
def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Given a function name and optional version qualifier, delete it. Returns {deleted: true} if the function was deleted and returns {deleted: false} if the function was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_function myfunction ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if Qualifier: conn.delete_function( FunctionName=FunctionName, Qualifier=Qualifier) else: conn.delete_function(FunctionName=FunctionName) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Given a function name and optional version qualifier, delete it. Returns {deleted: true} if the function was deleted and returns {deleted: false} if the function was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_function myfunction ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if Qualifier: conn.delete_function( FunctionName=FunctionName, Qualifier=Qualifier) else: conn.delete_function(FunctionName=FunctionName) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_function", "(", "FunctionName", ",", "Qualifier", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", ...
Given a function name and optional version qualifier, delete it. Returns {deleted: true} if the function was deleted and returns {deleted: false} if the function was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_function myfunction
[ "Given", "a", "function", "name", "and", "optional", "version", "qualifier", "delete", "it", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L311-L335
train
saltstack/salt
salt/modules/boto_lambda.py
describe_function
def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given a function name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_function myfunction ''' try: func = _find_function(FunctionName, region=region, key=key, keyid=keyid, profile=profile) if func: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig', 'Environment') return {'function': dict([(k, func.get(k)) for k in keys])} else: return {'function': None} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given a function name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_function myfunction ''' try: func = _find_function(FunctionName, region=region, key=key, keyid=keyid, profile=profile) if func: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig', 'Environment') return {'function': dict([(k, func.get(k)) for k in keys])} else: return {'function': None} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_function", "(", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "func", "=", "_find_function", "(", "FunctionName", ",", "region", "=", ...
Given a function name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_function myfunction
[ "Given", "a", "function", "name", "describe", "its", "properties", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L338-L364
train
saltstack/salt
salt/modules/boto_lambda.py
update_function_config
def update_function_config(FunctionName, Role=None, Handler=None, Description=None, Timeout=None, MemorySize=None, region=None, key=None, keyid=None, profile=None, VpcConfig=None, WaitForRole=False, RoleRetries=5, Environment=None): ''' .. versionadded:: 2017.7.0 Update the named lambda function to the configuration. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } Returns ``{'updated': True}`` if the function was updated, and ``{'updated': False}`` if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_config my_function my_role my_file.my_function "my lambda function" ''' args = dict(FunctionName=FunctionName) options = {'Handler': Handler, 'Description': Description, 'Timeout': Timeout, 'MemorySize': MemorySize, 'VpcConfig': VpcConfig, 'Environment': Environment} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for val, var in six.iteritems(options): if var: args[val] = var if Role: args['Role'] = _get_role_arn(Role, region, key, keyid, profile) if VpcConfig: args['VpcConfig'] = _resolve_vpcconfig(VpcConfig, region=region, key=key, keyid=keyid, profile=profile) try: if WaitForRole: retrycount = RoleRetries else: retrycount = 1 for retry in range(retrycount, 0, -1): try: r = conn.update_function_configuration(**args) except ClientError as e: if retry > 1 and e.response.get('Error', {}).get('Code') == 'InvalidParameterValueException': log.info( 'Function not updated but IAM role may not have propagated, will retry') # exponential backoff time.sleep((2 ** (RoleRetries - retry)) + (random.randint(0, 1000) / 1000)) continue else: raise else: break if r: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig', 'Environment') return {'updated': True, 'function': dict([(k, r.get(k)) for k in keys])} else: log.warning('Function was not updated') return {'updated': False} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
python
def update_function_config(FunctionName, Role=None, Handler=None, Description=None, Timeout=None, MemorySize=None, region=None, key=None, keyid=None, profile=None, VpcConfig=None, WaitForRole=False, RoleRetries=5, Environment=None): ''' .. versionadded:: 2017.7.0 Update the named lambda function to the configuration. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } Returns ``{'updated': True}`` if the function was updated, and ``{'updated': False}`` if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_config my_function my_role my_file.my_function "my lambda function" ''' args = dict(FunctionName=FunctionName) options = {'Handler': Handler, 'Description': Description, 'Timeout': Timeout, 'MemorySize': MemorySize, 'VpcConfig': VpcConfig, 'Environment': Environment} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for val, var in six.iteritems(options): if var: args[val] = var if Role: args['Role'] = _get_role_arn(Role, region, key, keyid, profile) if VpcConfig: args['VpcConfig'] = _resolve_vpcconfig(VpcConfig, region=region, key=key, keyid=keyid, profile=profile) try: if WaitForRole: retrycount = RoleRetries else: retrycount = 1 for retry in range(retrycount, 0, -1): try: r = conn.update_function_configuration(**args) except ClientError as e: if retry > 1 and e.response.get('Error', {}).get('Code') == 'InvalidParameterValueException': log.info( 'Function not updated but IAM role may not have propagated, will retry') # exponential backoff time.sleep((2 ** (RoleRetries - retry)) + (random.randint(0, 1000) / 1000)) continue else: raise else: break if r: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig', 'Environment') return {'updated': True, 'function': dict([(k, r.get(k)) for k in keys])} else: log.warning('Function was not updated') return {'updated': False} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update_function_config", "(", "FunctionName", ",", "Role", "=", "None", ",", "Handler", "=", "None", ",", "Description", "=", "None", ",", "Timeout", "=", "None", ",", "MemorySize", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None"...
.. versionadded:: 2017.7.0 Update the named lambda function to the configuration. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } Returns ``{'updated': True}`` if the function was updated, and ``{'updated': False}`` if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_config my_function my_role my_file.my_function "my lambda function"
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L367-L445
train
saltstack/salt
salt/modules/boto_lambda.py
update_function_code
def update_function_code(FunctionName, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Publish=False, region=None, key=None, keyid=None, profile=None): ''' Upload the given code to the named lambda function. Returns {updated: true} if the function was updated and returns {updated: False} if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if ZipFile: if S3Bucket or S3Key or S3ObjectVersion: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') r = conn.update_function_code(FunctionName=FunctionName, ZipFile=_filedata(ZipFile), Publish=Publish) else: if not S3Bucket or not S3Key: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') args = { 'S3Bucket': S3Bucket, 'S3Key': S3Key, } if S3ObjectVersion: args['S3ObjectVersion'] = S3ObjectVersion r = conn.update_function_code(FunctionName=FunctionName, Publish=Publish, **args) if r: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig', 'Environment') return {'updated': True, 'function': dict([(k, r.get(k)) for k in keys])} else: log.warning('Function was not updated') return {'updated': False} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
python
def update_function_code(FunctionName, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Publish=False, region=None, key=None, keyid=None, profile=None): ''' Upload the given code to the named lambda function. Returns {updated: true} if the function was updated and returns {updated: False} if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if ZipFile: if S3Bucket or S3Key or S3ObjectVersion: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') r = conn.update_function_code(FunctionName=FunctionName, ZipFile=_filedata(ZipFile), Publish=Publish) else: if not S3Bucket or not S3Key: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') args = { 'S3Bucket': S3Bucket, 'S3Key': S3Key, } if S3ObjectVersion: args['S3ObjectVersion'] = S3ObjectVersion r = conn.update_function_code(FunctionName=FunctionName, Publish=Publish, **args) if r: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig', 'Environment') return {'updated': True, 'function': dict([(k, r.get(k)) for k in keys])} else: log.warning('Function was not updated') return {'updated': False} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update_function_code", "(", "FunctionName", ",", "ZipFile", "=", "None", ",", "S3Bucket", "=", "None", ",", "S3Key", "=", "None", ",", "S3ObjectVersion", "=", "None", ",", "Publish", "=", "False", ",", "region", "=", "None", ",", "key", "=", "Non...
Upload the given code to the named lambda function. Returns {updated: true} if the function was updated and returns {updated: False} if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip
[ "Upload", "the", "given", "code", "to", "the", "named", "lambda", "function", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L448-L495
train
saltstack/salt
salt/modules/boto_lambda.py
add_permission
def add_permission(FunctionName, StatementId, Action, Principal, SourceArn=None, SourceAccount=None, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Add a permission to a lambda function. Returns {added: true} if the permission was added and returns {added: False} if the permission was not added. CLI Example: .. code-block:: bash salt myminion boto_lamba.add_permission my_function my_id "lambda:*" \\ s3.amazonaws.com aws:arn::::bucket-name \\ aws-account-id ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} for key in ('SourceArn', 'SourceAccount', 'Qualifier'): if locals()[key] is not None: kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function conn.add_permission(FunctionName=FunctionName, StatementId=StatementId, Action=Action, Principal=str(Principal), # future lint: disable=blacklisted-function **kwargs) return {'updated': True} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
python
def add_permission(FunctionName, StatementId, Action, Principal, SourceArn=None, SourceAccount=None, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Add a permission to a lambda function. Returns {added: true} if the permission was added and returns {added: False} if the permission was not added. CLI Example: .. code-block:: bash salt myminion boto_lamba.add_permission my_function my_id "lambda:*" \\ s3.amazonaws.com aws:arn::::bucket-name \\ aws-account-id ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} for key in ('SourceArn', 'SourceAccount', 'Qualifier'): if locals()[key] is not None: kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function conn.add_permission(FunctionName=FunctionName, StatementId=StatementId, Action=Action, Principal=str(Principal), # future lint: disable=blacklisted-function **kwargs) return {'updated': True} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "add_permission", "(", "FunctionName", ",", "StatementId", ",", "Action", ",", "Principal", ",", "SourceArn", "=", "None", ",", "SourceAccount", "=", "None", ",", "Qualifier", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", ...
Add a permission to a lambda function. Returns {added: true} if the permission was added and returns {added: False} if the permission was not added. CLI Example: .. code-block:: bash salt myminion boto_lamba.add_permission my_function my_id "lambda:*" \\ s3.amazonaws.com aws:arn::::bucket-name \\ aws-account-id
[ "Add", "a", "permission", "to", "a", "lambda", "function", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L498-L528
train
saltstack/salt
salt/modules/boto_lambda.py
remove_permission
def remove_permission(FunctionName, StatementId, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Remove a permission from a lambda function. Returns {removed: true} if the permission was removed and returns {removed: False} if the permission was not removed. CLI Example: .. code-block:: bash salt myminion boto_lamba.remove_permission my_function my_id ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} if Qualifier is not None: kwargs['Qualifier'] = Qualifier conn.remove_permission(FunctionName=FunctionName, StatementId=StatementId, **kwargs) return {'updated': True} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
python
def remove_permission(FunctionName, StatementId, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Remove a permission from a lambda function. Returns {removed: true} if the permission was removed and returns {removed: False} if the permission was not removed. CLI Example: .. code-block:: bash salt myminion boto_lamba.remove_permission my_function my_id ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} if Qualifier is not None: kwargs['Qualifier'] = Qualifier conn.remove_permission(FunctionName=FunctionName, StatementId=StatementId, **kwargs) return {'updated': True} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "remove_permission", "(", "FunctionName", ",", "StatementId", ",", "Qualifier", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_co...
Remove a permission from a lambda function. Returns {removed: true} if the permission was removed and returns {removed: False} if the permission was not removed. CLI Example: .. code-block:: bash salt myminion boto_lamba.remove_permission my_function my_id
[ "Remove", "a", "permission", "from", "a", "lambda", "function", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L531-L556
train
saltstack/salt
salt/modules/boto_lambda.py
get_permissions
def get_permissions(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Get resource permissions for the given lambda function Returns dictionary of permissions, by statement ID CLI Example: .. code-block:: bash salt myminion boto_lamba.get_permissions my_function permissions: {...} ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} if Qualifier is not None: kwargs['Qualifier'] = Qualifier # The get_policy call is not symmetric with add/remove_permissions. So # massage it until it is, for better ease of use. policy = conn.get_policy(FunctionName=FunctionName, **kwargs) policy = policy.get('Policy', {}) if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy) if policy is None: policy = {} permissions = {} for statement in policy.get('Statement', []): condition = statement.get('Condition', {}) principal = statement.get('Principal', {}) if 'AWS' in principal: principal = principal['AWS'].split(':')[4] else: principal = principal.get('Service') permission = { 'Action': statement.get('Action'), 'Principal': principal, } if 'ArnLike' in condition: permission['SourceArn'] = condition[ 'ArnLike'].get('AWS:SourceArn') if 'StringEquals' in condition: permission['SourceAccount'] = condition[ 'StringEquals'].get('AWS:SourceAccount') permissions[statement.get('Sid')] = permission return {'permissions': permissions} except ClientError as e: err = __utils__['boto3.get_error'](e) if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException': return {'permissions': None} return {'permissions': None, 'error': err}
python
def get_permissions(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Get resource permissions for the given lambda function Returns dictionary of permissions, by statement ID CLI Example: .. code-block:: bash salt myminion boto_lamba.get_permissions my_function permissions: {...} ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} if Qualifier is not None: kwargs['Qualifier'] = Qualifier # The get_policy call is not symmetric with add/remove_permissions. So # massage it until it is, for better ease of use. policy = conn.get_policy(FunctionName=FunctionName, **kwargs) policy = policy.get('Policy', {}) if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy) if policy is None: policy = {} permissions = {} for statement in policy.get('Statement', []): condition = statement.get('Condition', {}) principal = statement.get('Principal', {}) if 'AWS' in principal: principal = principal['AWS'].split(':')[4] else: principal = principal.get('Service') permission = { 'Action': statement.get('Action'), 'Principal': principal, } if 'ArnLike' in condition: permission['SourceArn'] = condition[ 'ArnLike'].get('AWS:SourceArn') if 'StringEquals' in condition: permission['SourceAccount'] = condition[ 'StringEquals'].get('AWS:SourceAccount') permissions[statement.get('Sid')] = permission return {'permissions': permissions} except ClientError as e: err = __utils__['boto3.get_error'](e) if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException': return {'permissions': None} return {'permissions': None, 'error': err}
[ "def", "get_permissions", "(", "FunctionName", ",", "Qualifier", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", ...
Get resource permissions for the given lambda function Returns dictionary of permissions, by statement ID CLI Example: .. code-block:: bash salt myminion boto_lamba.get_permissions my_function permissions: {...}
[ "Get", "resource", "permissions", "for", "the", "given", "lambda", "function" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L559-L613
train
saltstack/salt
salt/modules/boto_lambda.py
list_functions
def list_functions(region=None, key=None, keyid=None, profile=None): ''' List all Lambda functions visible in the current scope. CLI Example: .. code-block:: bash salt myminion boto_lambda.list_functions ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = [] for funcs in __utils__['boto3.paged_call'](conn.list_functions): ret += funcs['Functions'] return ret
python
def list_functions(region=None, key=None, keyid=None, profile=None): ''' List all Lambda functions visible in the current scope. CLI Example: .. code-block:: bash salt myminion boto_lambda.list_functions ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = [] for funcs in __utils__['boto3.paged_call'](conn.list_functions): ret += funcs['Functions'] return ret
[ "def", "list_functions", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyi...
List all Lambda functions visible in the current scope. CLI Example: .. code-block:: bash salt myminion boto_lambda.list_functions
[ "List", "all", "Lambda", "functions", "visible", "in", "the", "current", "scope", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L616-L632
train
saltstack/salt
salt/modules/boto_lambda.py
list_function_versions
def list_function_versions(FunctionName, region=None, key=None, keyid=None, profile=None): ''' List the versions available for the given function. Returns list of function versions CLI Example: .. code-block:: yaml versions: - {...} - {...} ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vers = [] for ret in __utils__['boto3.paged_call'](conn.list_versions_by_function, FunctionName=FunctionName): vers.extend(ret['Versions']) if not bool(vers): log.warning('No versions found') return {'Versions': vers} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def list_function_versions(FunctionName, region=None, key=None, keyid=None, profile=None): ''' List the versions available for the given function. Returns list of function versions CLI Example: .. code-block:: yaml versions: - {...} - {...} ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vers = [] for ret in __utils__['boto3.paged_call'](conn.list_versions_by_function, FunctionName=FunctionName): vers.extend(ret['Versions']) if not bool(vers): log.warning('No versions found') return {'Versions': vers} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "list_function_versions", "(", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key",...
List the versions available for the given function. Returns list of function versions CLI Example: .. code-block:: yaml versions: - {...} - {...}
[ "List", "the", "versions", "available", "for", "the", "given", "function", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L635-L661
train
saltstack/salt
salt/modules/boto_lambda.py
create_alias
def create_alias(FunctionName, Name, FunctionVersion, Description="", region=None, key=None, keyid=None, profile=None): ''' Given a valid config, create an alias to a function. Returns {created: true} if the alias was created and returns {created: False} if the alias was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_alias my_function my_alias $LATEST "An alias" ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) alias = conn.create_alias(FunctionName=FunctionName, Name=Name, FunctionVersion=FunctionVersion, Description=Description) if alias: log.info('The newly created alias name is %s', alias['Name']) return {'created': True, 'name': alias['Name']} else: log.warning('Alias was not created') return {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_alias(FunctionName, Name, FunctionVersion, Description="", region=None, key=None, keyid=None, profile=None): ''' Given a valid config, create an alias to a function. Returns {created: true} if the alias was created and returns {created: False} if the alias was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_alias my_function my_alias $LATEST "An alias" ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) alias = conn.create_alias(FunctionName=FunctionName, Name=Name, FunctionVersion=FunctionVersion, Description=Description) if alias: log.info('The newly created alias name is %s', alias['Name']) return {'created': True, 'name': alias['Name']} else: log.warning('Alias was not created') return {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_alias", "(", "FunctionName", ",", "Name", ",", "FunctionVersion", ",", "Description", "=", "\"\"", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn",...
Given a valid config, create an alias to a function. Returns {created: true} if the alias was created and returns {created: False} if the alias was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_alias my_function my_alias $LATEST "An alias"
[ "Given", "a", "valid", "config", "create", "an", "alias", "to", "a", "function", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L664-L691
train
saltstack/salt
salt/modules/boto_lambda.py
_find_alias
def _find_alias(FunctionName, Name, FunctionVersion=None, region=None, key=None, keyid=None, profile=None): ''' Given function name and alias name, find and return matching alias information. ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = { 'FunctionName': FunctionName } if FunctionVersion: args['FunctionVersion'] = FunctionVersion for aliases in __utils__['boto3.paged_call'](conn.list_aliases, **args): for alias in aliases.get('Aliases'): if alias['Name'] == Name: return alias return None
python
def _find_alias(FunctionName, Name, FunctionVersion=None, region=None, key=None, keyid=None, profile=None): ''' Given function name and alias name, find and return matching alias information. ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = { 'FunctionName': FunctionName } if FunctionVersion: args['FunctionVersion'] = FunctionVersion for aliases in __utils__['boto3.paged_call'](conn.list_aliases, **args): for alias in aliases.get('Aliases'): if alias['Name'] == Name: return alias return None
[ "def", "_find_alias", "(", "FunctionName", ",", "Name", ",", "FunctionVersion", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region",...
Given function name and alias name, find and return matching alias information.
[ "Given", "function", "name", "and", "alias", "name", "find", "and", "return", "matching", "alias", "information", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L717-L734
train
saltstack/salt
salt/modules/boto_lambda.py
alias_exists
def alias_exists(FunctionName, Name, region=None, key=None, keyid=None, profile=None): ''' Given a function name and alias name, check to see if the given alias exists. Returns True if the given alias exists and returns False if the given alias does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.alias_exists myfunction myalias ''' try: alias = _find_alias(FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(alias)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def alias_exists(FunctionName, Name, region=None, key=None, keyid=None, profile=None): ''' Given a function name and alias name, check to see if the given alias exists. Returns True if the given alias exists and returns False if the given alias does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.alias_exists myfunction myalias ''' try: alias = _find_alias(FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(alias)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "alias_exists", "(", "FunctionName", ",", "Name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "alias", "=", "_find_alias", "(", "FunctionName", ",", "Name", ...
Given a function name and alias name, check to see if the given alias exists. Returns True if the given alias exists and returns False if the given alias does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.alias_exists myfunction myalias
[ "Given", "a", "function", "name", "and", "alias", "name", "check", "to", "see", "if", "the", "given", "alias", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L737-L758
train
saltstack/salt
salt/modules/boto_lambda.py
describe_alias
def describe_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None): ''' Given a function name and alias name describe the properties of the alias. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_alias myalias ''' try: alias = _find_alias(FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile) if alias: keys = ('AliasArn', 'Name', 'FunctionVersion', 'Description') return {'alias': dict([(k, alias.get(k)) for k in keys])} else: return {'alias': None} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_alias(FunctionName, Name, region=None, key=None, keyid=None, profile=None): ''' Given a function name and alias name describe the properties of the alias. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_alias myalias ''' try: alias = _find_alias(FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile) if alias: keys = ('AliasArn', 'Name', 'FunctionVersion', 'Description') return {'alias': dict([(k, alias.get(k)) for k in keys])} else: return {'alias': None} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_alias", "(", "FunctionName", ",", "Name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "alias", "=", "_find_alias", "(", "FunctionName", ",", "Name",...
Given a function name and alias name describe the properties of the alias. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_alias myalias
[ "Given", "a", "function", "name", "and", "alias", "name", "describe", "the", "properties", "of", "the", "alias", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L761-L785
train
saltstack/salt
salt/modules/boto_lambda.py
update_alias
def update_alias(FunctionName, Name, FunctionVersion=None, Description=None, region=None, key=None, keyid=None, profile=None): ''' Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_alias my_lambda my_alias $LATEST ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {} if FunctionVersion: args['FunctionVersion'] = FunctionVersion if Description: args['Description'] = Description r = conn.update_alias(FunctionName=FunctionName, Name=Name, **args) if r: keys = ('Name', 'FunctionVersion', 'Description') return {'updated': True, 'alias': dict([(k, r.get(k)) for k in keys])} else: log.warning('Alias was not updated') return {'updated': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def update_alias(FunctionName, Name, FunctionVersion=None, Description=None, region=None, key=None, keyid=None, profile=None): ''' Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_alias my_lambda my_alias $LATEST ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {} if FunctionVersion: args['FunctionVersion'] = FunctionVersion if Description: args['Description'] = Description r = conn.update_alias(FunctionName=FunctionName, Name=Name, **args) if r: keys = ('Name', 'FunctionVersion', 'Description') return {'updated': True, 'alias': dict([(k, r.get(k)) for k in keys])} else: log.warning('Alias was not updated') return {'updated': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update_alias", "(", "FunctionName", ",", "Name", ",", "FunctionVersion", "=", "None", ",", "Description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try",...
Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_alias my_lambda my_alias $LATEST
[ "Update", "the", "named", "alias", "to", "the", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L788-L819
train
saltstack/salt
salt/modules/boto_lambda.py
create_event_source_mapping
def create_event_source_mapping(EventSourceArn, FunctionName, StartingPosition, Enabled=True, BatchSize=100, region=None, key=None, keyid=None, profile=None): ''' Identifies a stream as an event source for a Lambda function. It can be either an Amazon Kinesis stream or an Amazon DynamoDB stream. AWS Lambda invokes the specified function when records are posted to the stream. Returns {created: true} if the event source mapping was created and returns {created: False} if the event source mapping was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_event_source_mapping arn::::eventsource myfunction LATEST ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) obj = conn.create_event_source_mapping(EventSourceArn=EventSourceArn, FunctionName=FunctionName, Enabled=Enabled, BatchSize=BatchSize, StartingPosition=StartingPosition) if obj: log.info('The newly created event source mapping ID is %s', obj['UUID']) return {'created': True, 'id': obj['UUID']} else: log.warning('Event source mapping was not created') return {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_event_source_mapping(EventSourceArn, FunctionName, StartingPosition, Enabled=True, BatchSize=100, region=None, key=None, keyid=None, profile=None): ''' Identifies a stream as an event source for a Lambda function. It can be either an Amazon Kinesis stream or an Amazon DynamoDB stream. AWS Lambda invokes the specified function when records are posted to the stream. Returns {created: true} if the event source mapping was created and returns {created: False} if the event source mapping was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_event_source_mapping arn::::eventsource myfunction LATEST ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) obj = conn.create_event_source_mapping(EventSourceArn=EventSourceArn, FunctionName=FunctionName, Enabled=Enabled, BatchSize=BatchSize, StartingPosition=StartingPosition) if obj: log.info('The newly created event source mapping ID is %s', obj['UUID']) return {'created': True, 'id': obj['UUID']} else: log.warning('Event source mapping was not created') return {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_event_source_mapping", "(", "EventSourceArn", ",", "FunctionName", ",", "StartingPosition", ",", "Enabled", "=", "True", ",", "BatchSize", "=", "100", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profil...
Identifies a stream as an event source for a Lambda function. It can be either an Amazon Kinesis stream or an Amazon DynamoDB stream. AWS Lambda invokes the specified function when records are posted to the stream. Returns {created: true} if the event source mapping was created and returns {created: False} if the event source mapping was not created. CLI Example: .. code-block:: bash salt myminion boto_lamba.create_event_source_mapping arn::::eventsource myfunction LATEST
[ "Identifies", "a", "stream", "as", "an", "event", "source", "for", "a", "Lambda", "function", ".", "It", "can", "be", "either", "an", "Amazon", "Kinesis", "stream", "or", "an", "Amazon", "DynamoDB", "stream", ".", "AWS", "Lambda", "invokes", "the", "specif...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L822-L855
train
saltstack/salt
salt/modules/boto_lambda.py
get_event_source_mapping_ids
def get_event_source_mapping_ids(EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given an event source and function name, return a list of mapping IDs CLI Example: .. code-block:: bash salt myminion boto_lambda.get_event_source_mapping_ids arn:::: myfunction ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: mappings = [] for maps in __utils__['boto3.paged_call'](conn.list_event_source_mappings, EventSourceArn=EventSourceArn, FunctionName=FunctionName): mappings.extend([mapping['UUID'] for mapping in maps['EventSourceMappings']]) return mappings except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def get_event_source_mapping_ids(EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given an event source and function name, return a list of mapping IDs CLI Example: .. code-block:: bash salt myminion boto_lambda.get_event_source_mapping_ids arn:::: myfunction ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: mappings = [] for maps in __utils__['boto3.paged_call'](conn.list_event_source_mappings, EventSourceArn=EventSourceArn, FunctionName=FunctionName): mappings.extend([mapping['UUID'] for mapping in maps['EventSourceMappings']]) return mappings except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "get_event_source_mapping_ids", "(", "EventSourceArn", ",", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region"...
Given an event source and function name, return a list of mapping IDs CLI Example: .. code-block:: bash salt myminion boto_lambda.get_event_source_mapping_ids arn:::: myfunction
[ "Given", "an", "event", "source", "and", "function", "name", "return", "a", "list", "of", "mapping", "IDs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L858-L881
train
saltstack/salt
salt/modules/boto_lambda.py
delete_event_source_mapping
def delete_event_source_mapping(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, delete the event source mapping Returns {deleted: true} if the mapping was deleted and returns {deleted: false} if the mapping was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_event_source_mapping 260c423d-e8b5-4443-8d6a-5e91b9ecd0fa ''' ids = _get_ids(UUID, EventSourceArn=EventSourceArn, FunctionName=FunctionName) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for id in ids: conn.delete_event_source_mapping(UUID=id) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_event_source_mapping(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, delete the event source mapping Returns {deleted: true} if the mapping was deleted and returns {deleted: false} if the mapping was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_event_source_mapping 260c423d-e8b5-4443-8d6a-5e91b9ecd0fa ''' ids = _get_ids(UUID, EventSourceArn=EventSourceArn, FunctionName=FunctionName) try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for id in ids: conn.delete_event_source_mapping(UUID=id) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_event_source_mapping", "(", "UUID", "=", "None", ",", "EventSourceArn", "=", "None", ",", "FunctionName", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", ...
Given an event source mapping ID or an event source ARN and FunctionName, delete the event source mapping Returns {deleted: true} if the mapping was deleted and returns {deleted: false} if the mapping was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_event_source_mapping 260c423d-e8b5-4443-8d6a-5e91b9ecd0fa
[ "Given", "an", "event", "source", "mapping", "ID", "or", "an", "event", "source", "ARN", "and", "FunctionName", "delete", "the", "event", "source", "mapping" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L900-L924
train
saltstack/salt
salt/modules/boto_lambda.py
event_source_mapping_exists
def event_source_mapping_exists(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, check whether the mapping exists. Returns True if the given alias exists and returns False if the given alias does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.alias_exists myfunction myalias ''' desc = describe_event_source_mapping(UUID=UUID, EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in desc: return desc return {'exists': bool(desc.get('event_source_mapping'))}
python
def event_source_mapping_exists(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, check whether the mapping exists. Returns True if the given alias exists and returns False if the given alias does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.alias_exists myfunction myalias ''' desc = describe_event_source_mapping(UUID=UUID, EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in desc: return desc return {'exists': bool(desc.get('event_source_mapping'))}
[ "def", "event_source_mapping_exists", "(", "UUID", "=", "None", ",", "EventSourceArn", "=", "None", ",", "FunctionName", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", ...
Given an event source mapping ID or an event source ARN and FunctionName, check whether the mapping exists. Returns True if the given alias exists and returns False if the given alias does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.alias_exists myfunction myalias
[ "Given", "an", "event", "source", "mapping", "ID", "or", "an", "event", "source", "ARN", "and", "FunctionName", "check", "whether", "the", "mapping", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L927-L952
train
saltstack/salt
salt/modules/boto_lambda.py
describe_event_source_mapping
def describe_event_source_mapping(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, obtain the current settings of that mapping. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_event_source_mapping uuid ''' ids = _get_ids(UUID, EventSourceArn=EventSourceArn, FunctionName=FunctionName) if not ids: return {'event_source_mapping': None} UUID = ids[0] try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) desc = conn.get_event_source_mapping(UUID=UUID) if desc: keys = ('UUID', 'BatchSize', 'EventSourceArn', 'FunctionArn', 'LastModified', 'LastProcessingResult', 'State', 'StateTransitionReason') return {'event_source_mapping': dict([(k, desc.get(k)) for k in keys])} else: return {'event_source_mapping': None} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_event_source_mapping(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, obtain the current settings of that mapping. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_event_source_mapping uuid ''' ids = _get_ids(UUID, EventSourceArn=EventSourceArn, FunctionName=FunctionName) if not ids: return {'event_source_mapping': None} UUID = ids[0] try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) desc = conn.get_event_source_mapping(UUID=UUID) if desc: keys = ('UUID', 'BatchSize', 'EventSourceArn', 'FunctionArn', 'LastModified', 'LastProcessingResult', 'State', 'StateTransitionReason') return {'event_source_mapping': dict([(k, desc.get(k)) for k in keys])} else: return {'event_source_mapping': None} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_event_source_mapping", "(", "UUID", "=", "None", ",", "EventSourceArn", "=", "None", ",", "FunctionName", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":",...
Given an event source mapping ID or an event source ARN and FunctionName, obtain the current settings of that mapping. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_event_source_mapping uuid
[ "Given", "an", "event", "source", "mapping", "ID", "or", "an", "event", "source", "ARN", "and", "FunctionName", "obtain", "the", "current", "settings", "of", "that", "mapping", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L955-L989
train
saltstack/salt
salt/modules/boto_lambda.py
update_event_source_mapping
def update_event_source_mapping(UUID, FunctionName=None, Enabled=None, BatchSize=None, region=None, key=None, keyid=None, profile=None): ''' Update the event source mapping identified by the UUID. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_event_source_mapping uuid FunctionName=new_function ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {} if FunctionName is not None: args['FunctionName'] = FunctionName if Enabled is not None: args['Enabled'] = Enabled if BatchSize is not None: args['BatchSize'] = BatchSize r = conn.update_event_source_mapping(UUID=UUID, **args) if r: keys = ('UUID', 'BatchSize', 'EventSourceArn', 'FunctionArn', 'LastModified', 'LastProcessingResult', 'State', 'StateTransitionReason') return {'updated': True, 'event_source_mapping': dict([(k, r.get(k)) for k in keys])} else: log.warning('Mapping was not updated') return {'updated': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def update_event_source_mapping(UUID, FunctionName=None, Enabled=None, BatchSize=None, region=None, key=None, keyid=None, profile=None): ''' Update the event source mapping identified by the UUID. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_event_source_mapping uuid FunctionName=new_function ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {} if FunctionName is not None: args['FunctionName'] = FunctionName if Enabled is not None: args['Enabled'] = Enabled if BatchSize is not None: args['BatchSize'] = BatchSize r = conn.update_event_source_mapping(UUID=UUID, **args) if r: keys = ('UUID', 'BatchSize', 'EventSourceArn', 'FunctionArn', 'LastModified', 'LastProcessingResult', 'State', 'StateTransitionReason') return {'updated': True, 'event_source_mapping': dict([(k, r.get(k)) for k in keys])} else: log.warning('Mapping was not updated') return {'updated': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update_event_source_mapping", "(", "UUID", ",", "FunctionName", "=", "None", ",", "Enabled", "=", "None", ",", "BatchSize", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ...
Update the event source mapping identified by the UUID. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_event_source_mapping uuid FunctionName=new_function
[ "Update", "the", "event", "source", "mapping", "identified", "by", "the", "UUID", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L992-L1028
train
saltstack/salt
salt/fileserver/s3fs.py
update
def update(): ''' Update the cache file for the bucket. ''' metadata = _init() if S3_SYNC_ON_UPDATE: # sync the buckets to the local cache log.info('Syncing local cache from S3...') for saltenv, env_meta in six.iteritems(metadata): for bucket_files in _find_files(env_meta): for bucket, files in six.iteritems(bucket_files): for file_path in files: cached_file_path = _get_cached_file_name(bucket, saltenv, file_path) log.info('%s - %s : %s', bucket, saltenv, file_path) # load the file from S3 if it's not in the cache or it's old _get_file_from_s3(metadata, saltenv, bucket, file_path, cached_file_path) log.info('Sync local cache from S3 completed.')
python
def update(): ''' Update the cache file for the bucket. ''' metadata = _init() if S3_SYNC_ON_UPDATE: # sync the buckets to the local cache log.info('Syncing local cache from S3...') for saltenv, env_meta in six.iteritems(metadata): for bucket_files in _find_files(env_meta): for bucket, files in six.iteritems(bucket_files): for file_path in files: cached_file_path = _get_cached_file_name(bucket, saltenv, file_path) log.info('%s - %s : %s', bucket, saltenv, file_path) # load the file from S3 if it's not in the cache or it's old _get_file_from_s3(metadata, saltenv, bucket, file_path, cached_file_path) log.info('Sync local cache from S3 completed.')
[ "def", "update", "(", ")", ":", "metadata", "=", "_init", "(", ")", "if", "S3_SYNC_ON_UPDATE", ":", "# sync the buckets to the local cache", "log", ".", "info", "(", "'Syncing local cache from S3...'", ")", "for", "saltenv", ",", "env_meta", "in", "six", ".", "i...
Update the cache file for the bucket.
[ "Update", "the", "cache", "file", "for", "the", "bucket", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L121-L141
train
saltstack/salt
salt/fileserver/s3fs.py
find_file
def find_file(path, saltenv='base', **kwargs): ''' Look through the buckets cache file for a match. If the field is found, it is retrieved from S3 only if its cached version is missing, or if the MD5 does not match. ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') fnd = {'bucket': None, 'path': None} metadata = _init() if not metadata or saltenv not in metadata: return fnd env_files = _find_files(metadata[saltenv]) if not _is_env_per_bucket(): path = os.path.join(saltenv, path) # look for the files and check if they're ignored globally for bucket in env_files: for bucket_name, files in six.iteritems(bucket): if path in files and not fs.is_file_ignored(__opts__, path): fnd['bucket'] = bucket_name fnd['path'] = path break else: continue # only executes if we didn't break break if not fnd['path'] or not fnd['bucket']: return fnd cached_file_path = _get_cached_file_name(fnd['bucket'], saltenv, path) # jit load the file from S3 if it's not in the cache or it's old _get_file_from_s3(metadata, saltenv, fnd['bucket'], path, cached_file_path) return fnd
python
def find_file(path, saltenv='base', **kwargs): ''' Look through the buckets cache file for a match. If the field is found, it is retrieved from S3 only if its cached version is missing, or if the MD5 does not match. ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') fnd = {'bucket': None, 'path': None} metadata = _init() if not metadata or saltenv not in metadata: return fnd env_files = _find_files(metadata[saltenv]) if not _is_env_per_bucket(): path = os.path.join(saltenv, path) # look for the files and check if they're ignored globally for bucket in env_files: for bucket_name, files in six.iteritems(bucket): if path in files and not fs.is_file_ignored(__opts__, path): fnd['bucket'] = bucket_name fnd['path'] = path break else: continue # only executes if we didn't break break if not fnd['path'] or not fnd['bucket']: return fnd cached_file_path = _get_cached_file_name(fnd['bucket'], saltenv, path) # jit load the file from S3 if it's not in the cache or it's old _get_file_from_s3(metadata, saltenv, fnd['bucket'], path, cached_file_path) return fnd
[ "def", "find_file", "(", "path", ",", "saltenv", "=", "'base'", ",", "*", "*", "kwargs", ")", ":", "if", "'env'", "in", "kwargs", ":", "# \"env\" is not supported; Use \"saltenv\".", "kwargs", ".", "pop", "(", "'env'", ")", "fnd", "=", "{", "'bucket'", ":"...
Look through the buckets cache file for a match. If the field is found, it is retrieved from S3 only if its cached version is missing, or if the MD5 does not match.
[ "Look", "through", "the", "buckets", "cache", "file", "for", "a", "match", ".", "If", "the", "field", "is", "found", "it", "is", "retrieved", "from", "S3", "only", "if", "its", "cached", "version", "is", "missing", "or", "if", "the", "MD5", "does", "no...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L144-L185
train
saltstack/salt
salt/fileserver/s3fs.py
file_hash
def file_hash(load, fnd): ''' Return an MD5 file hash ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = {} if 'saltenv' not in load: return ret if 'path' not in fnd or 'bucket' not in fnd or not fnd['path']: return ret cached_file_path = _get_cached_file_name( fnd['bucket'], load['saltenv'], fnd['path']) if os.path.isfile(cached_file_path): ret['hsum'] = salt.utils.hashutils.get_hash(cached_file_path) ret['hash_type'] = 'md5' return ret
python
def file_hash(load, fnd): ''' Return an MD5 file hash ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = {} if 'saltenv' not in load: return ret if 'path' not in fnd or 'bucket' not in fnd or not fnd['path']: return ret cached_file_path = _get_cached_file_name( fnd['bucket'], load['saltenv'], fnd['path']) if os.path.isfile(cached_file_path): ret['hsum'] = salt.utils.hashutils.get_hash(cached_file_path) ret['hash_type'] = 'md5' return ret
[ "def", "file_hash", "(", "load", ",", "fnd", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "ret", "=", "{", "}", "if", "'saltenv'", "not", "in", "load", ":", "return", "...
Return an MD5 file hash
[ "Return", "an", "MD5", "file", "hash" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L188-L213
train
saltstack/salt
salt/fileserver/s3fs.py
serve_file
def serve_file(load, fnd): ''' Return a chunk from a file based on the data received ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = {'data': '', 'dest': ''} if 'path' not in load or 'loc' not in load or 'saltenv' not in load: return ret if 'path' not in fnd or 'bucket' not in fnd: return ret gzip = load.get('gzip', None) # get the saltenv/path file from the cache cached_file_path = _get_cached_file_name( fnd['bucket'], load['saltenv'], fnd['path']) ret['dest'] = _trim_env_off_path([fnd['path']], load['saltenv'])[0] with salt.utils.files.fopen(cached_file_path, 'rb') as fp_: fp_.seek(load['loc']) data = fp_.read(__opts__['file_buffer_size']) if data and six.PY3 and not salt.utils.files.is_binary(cached_file_path): data = data.decode(__salt_system_encoding__) if gzip and data: data = salt.utils.gzip_util.compress(data, gzip) ret['gzip'] = gzip ret['data'] = data return ret
python
def serve_file(load, fnd): ''' Return a chunk from a file based on the data received ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = {'data': '', 'dest': ''} if 'path' not in load or 'loc' not in load or 'saltenv' not in load: return ret if 'path' not in fnd or 'bucket' not in fnd: return ret gzip = load.get('gzip', None) # get the saltenv/path file from the cache cached_file_path = _get_cached_file_name( fnd['bucket'], load['saltenv'], fnd['path']) ret['dest'] = _trim_env_off_path([fnd['path']], load['saltenv'])[0] with salt.utils.files.fopen(cached_file_path, 'rb') as fp_: fp_.seek(load['loc']) data = fp_.read(__opts__['file_buffer_size']) if data and six.PY3 and not salt.utils.files.is_binary(cached_file_path): data = data.decode(__salt_system_encoding__) if gzip and data: data = salt.utils.gzip_util.compress(data, gzip) ret['gzip'] = gzip ret['data'] = data return ret
[ "def", "serve_file", "(", "load", ",", "fnd", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "ret", "=", "{", "'data'", ":", "''", ",", "'dest'", ":", "''", "}", "if", ...
Return a chunk from a file based on the data received
[ "Return", "a", "chunk", "from", "a", "file", "based", "on", "the", "data", "received" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L216-L252
train
saltstack/salt
salt/fileserver/s3fs.py
file_list
def file_list(load): ''' Return a list of all files on the file server in a specified environment ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = [] if 'saltenv' not in load: return ret saltenv = load['saltenv'] metadata = _init() if not metadata or saltenv not in metadata: return ret for bucket in _find_files(metadata[saltenv]): for buckets in six.itervalues(bucket): files = [f for f in buckets if not fs.is_file_ignored(__opts__, f)] ret += _trim_env_off_path(files, saltenv) return ret
python
def file_list(load): ''' Return a list of all files on the file server in a specified environment ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = [] if 'saltenv' not in load: return ret saltenv = load['saltenv'] metadata = _init() if not metadata or saltenv not in metadata: return ret for bucket in _find_files(metadata[saltenv]): for buckets in six.itervalues(bucket): files = [f for f in buckets if not fs.is_file_ignored(__opts__, f)] ret += _trim_env_off_path(files, saltenv) return ret
[ "def", "file_list", "(", "load", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "ret", "=", "[", "]", "if", "'saltenv'", "not", "in", "load", ":", "return", "ret", "saltenv...
Return a list of all files on the file server in a specified environment
[ "Return", "a", "list", "of", "all", "files", "on", "the", "file", "server", "in", "a", "specified", "environment" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L255-L278
train
saltstack/salt
salt/fileserver/s3fs.py
dir_list
def dir_list(load): ''' Return a list of all directories on the master ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = [] if 'saltenv' not in load: return ret saltenv = load['saltenv'] metadata = _init() if not metadata or saltenv not in metadata: return ret # grab all the dirs from the buckets cache file for bucket in _find_dirs(metadata[saltenv]): for dirs in six.itervalues(bucket): # trim env and trailing slash dirs = _trim_env_off_path(dirs, saltenv, trim_slash=True) # remove empty string left by the base env dir in single bucket mode ret += [_f for _f in dirs if _f] return ret
python
def dir_list(load): ''' Return a list of all directories on the master ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = [] if 'saltenv' not in load: return ret saltenv = load['saltenv'] metadata = _init() if not metadata or saltenv not in metadata: return ret # grab all the dirs from the buckets cache file for bucket in _find_dirs(metadata[saltenv]): for dirs in six.itervalues(bucket): # trim env and trailing slash dirs = _trim_env_off_path(dirs, saltenv, trim_slash=True) # remove empty string left by the base env dir in single bucket mode ret += [_f for _f in dirs if _f] return ret
[ "def", "dir_list", "(", "load", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "ret", "=", "[", "]", "if", "'saltenv'", "not", "in", "load", ":", "return", "ret", "saltenv"...
Return a list of all directories on the master
[ "Return", "a", "list", "of", "all", "directories", "on", "the", "master" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L291-L318
train
saltstack/salt
salt/fileserver/s3fs.py
_get_s3_key
def _get_s3_key(): ''' Get AWS keys from pillar or config ''' key = __opts__['s3.key'] if 's3.key' in __opts__ else None keyid = __opts__['s3.keyid'] if 's3.keyid' in __opts__ else None service_url = __opts__['s3.service_url'] \ if 's3.service_url' in __opts__ \ else None verify_ssl = __opts__['s3.verify_ssl'] \ if 's3.verify_ssl' in __opts__ \ else None kms_keyid = __opts__['aws.kmw.keyid'] if 'aws.kms.keyid' in __opts__ else None location = __opts__['s3.location'] \ if 's3.location' in __opts__ \ else None path_style = __opts__['s3.path_style'] \ if 's3.path_style' in __opts__ \ else None https_enable = __opts__['s3.https_enable'] \ if 's3.https_enable' in __opts__ \ else None return key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable
python
def _get_s3_key(): ''' Get AWS keys from pillar or config ''' key = __opts__['s3.key'] if 's3.key' in __opts__ else None keyid = __opts__['s3.keyid'] if 's3.keyid' in __opts__ else None service_url = __opts__['s3.service_url'] \ if 's3.service_url' in __opts__ \ else None verify_ssl = __opts__['s3.verify_ssl'] \ if 's3.verify_ssl' in __opts__ \ else None kms_keyid = __opts__['aws.kmw.keyid'] if 'aws.kms.keyid' in __opts__ else None location = __opts__['s3.location'] \ if 's3.location' in __opts__ \ else None path_style = __opts__['s3.path_style'] \ if 's3.path_style' in __opts__ \ else None https_enable = __opts__['s3.https_enable'] \ if 's3.https_enable' in __opts__ \ else None return key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable
[ "def", "_get_s3_key", "(", ")", ":", "key", "=", "__opts__", "[", "'s3.key'", "]", "if", "'s3.key'", "in", "__opts__", "else", "None", "keyid", "=", "__opts__", "[", "'s3.keyid'", "]", "if", "'s3.keyid'", "in", "__opts__", "else", "None", "service_url", "=...
Get AWS keys from pillar or config
[ "Get", "AWS", "keys", "from", "pillar", "or", "config" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L321-L345
train
saltstack/salt
salt/fileserver/s3fs.py
_init
def _init(): ''' Connect to S3 and download the metadata for each file in all buckets specified and cache the data to disk. ''' cache_file = _get_buckets_cache_filename() exp = time.time() - S3_CACHE_EXPIRE # check mtime of the buckets files cache metadata = None try: if os.path.getmtime(cache_file) > exp: metadata = _read_buckets_cache_file(cache_file) except OSError: pass if metadata is None: # bucket files cache expired or does not exist metadata = _refresh_buckets_cache_file(cache_file) return metadata
python
def _init(): ''' Connect to S3 and download the metadata for each file in all buckets specified and cache the data to disk. ''' cache_file = _get_buckets_cache_filename() exp = time.time() - S3_CACHE_EXPIRE # check mtime of the buckets files cache metadata = None try: if os.path.getmtime(cache_file) > exp: metadata = _read_buckets_cache_file(cache_file) except OSError: pass if metadata is None: # bucket files cache expired or does not exist metadata = _refresh_buckets_cache_file(cache_file) return metadata
[ "def", "_init", "(", ")", ":", "cache_file", "=", "_get_buckets_cache_filename", "(", ")", "exp", "=", "time", ".", "time", "(", ")", "-", "S3_CACHE_EXPIRE", "# check mtime of the buckets files cache", "metadata", "=", "None", "try", ":", "if", "os", ".", "pat...
Connect to S3 and download the metadata for each file in all buckets specified and cache the data to disk.
[ "Connect", "to", "S3", "and", "download", "the", "metadata", "for", "each", "file", "in", "all", "buckets", "specified", "and", "cache", "the", "data", "to", "disk", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L348-L368
train
saltstack/salt
salt/fileserver/s3fs.py
_get_cached_file_name
def _get_cached_file_name(bucket_name, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket_name, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path
python
def _get_cached_file_name(bucket_name, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket_name, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path
[ "def", "_get_cached_file_name", "(", "bucket_name", ",", "saltenv", ",", "path", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "_get_cache_dir", "(", ")", ",", "saltenv", ",", "bucket_name", ",", "path", ")", "# make sure bucket and saltenv ...
Return the cached file name for a bucket path file
[ "Return", "the", "cached", "file", "name", "for", "a", "bucket", "path", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L380-L391
train
saltstack/salt
salt/fileserver/s3fs.py
_get_buckets_cache_filename
def _get_buckets_cache_filename(): ''' Return the filename of the cache for bucket contents. Create the path if it does not exist. ''' cache_dir = _get_cache_dir() if not os.path.exists(cache_dir): os.makedirs(cache_dir) return os.path.join(cache_dir, 'buckets_files.cache')
python
def _get_buckets_cache_filename(): ''' Return the filename of the cache for bucket contents. Create the path if it does not exist. ''' cache_dir = _get_cache_dir() if not os.path.exists(cache_dir): os.makedirs(cache_dir) return os.path.join(cache_dir, 'buckets_files.cache')
[ "def", "_get_buckets_cache_filename", "(", ")", ":", "cache_dir", "=", "_get_cache_dir", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cache_dir", ")", ":", "os", ".", "makedirs", "(", "cache_dir", ")", "return", "os", ".", "path", ".", ...
Return the filename of the cache for bucket contents. Create the path if it does not exist.
[ "Return", "the", "filename", "of", "the", "cache", "for", "bucket", "contents", ".", "Create", "the", "path", "if", "it", "does", "not", "exist", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L394-L404
train
saltstack/salt
salt/fileserver/s3fs.py
_refresh_buckets_cache_file
def _refresh_buckets_cache_file(cache_file): ''' Retrieve the content of all buckets and cache the metadata to the buckets cache file ''' log.debug('Refreshing buckets cache file') key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable = _get_s3_key() metadata = {} # helper s3 query function def __get_s3_meta(bucket, key=key, keyid=keyid): ret, marker = [], '' while True: tmp = __utils__['s3.query'](key=key, keyid=keyid, kms_keyid=keyid, bucket=bucket, service_url=service_url, verify_ssl=verify_ssl, location=location, return_bin=False, path_style=path_style, https_enable=https_enable, params={'marker': marker}) headers = [] for header in tmp: if 'Key' in header: break headers.append(header) ret.extend(tmp) if all([header.get('IsTruncated', 'false') == 'false' for header in headers]): break marker = tmp[-1]['Key'] return ret if _is_env_per_bucket(): # Single environment per bucket for saltenv, buckets in six.iteritems(_get_buckets()): bucket_files_list = [] for bucket_name in buckets: bucket_files = {} s3_meta = __get_s3_meta(bucket_name) # s3 query returned nothing if not s3_meta: continue # grab only the files/dirs bucket_files[bucket_name] = [k for k in s3_meta if 'Key' in k] bucket_files_list.append(bucket_files) # check to see if we added any keys, otherwise investigate possible error conditions if not bucket_files[bucket_name]: meta_response = {} for k in s3_meta: if 'Code' in k or 'Message' in k: # assumes no duplicate keys, consisdent with current erro response. meta_response.update(k) # attempt use of human readable output first. try: log.warning("'%s' response for bucket '%s'", meta_response['Message'], bucket_name) continue except KeyError: # no human readable error message provided if 'Code' in meta_response: log.warning( "'%s' response for bucket '%s'", meta_response['Code'], bucket_name ) continue else: log.warning( 'S3 Error! Do you have any files ' 'in your S3 bucket?') return {} metadata[saltenv] = bucket_files_list else: # Multiple environments per buckets for bucket_name in _get_buckets(): s3_meta = __get_s3_meta(bucket_name) # s3 query returned nothing if not s3_meta: continue # pull out the environment dirs (e.g. the root dirs) files = [k for k in s3_meta if 'Key' in k] # check to see if we added any keys, otherwise investigate possible error conditions if not files: meta_response = {} for k in s3_meta: if 'Code' in k or 'Message' in k: # assumes no duplicate keys, consisdent with current erro response. meta_response.update(k) # attempt use of human readable output first. try: log.warning("'%s' response for bucket '%s'", meta_response['Message'], bucket_name) continue except KeyError: # no human readable error message provided if 'Code' in meta_response: log.warning( "'%s' response for bucket '%s'", meta_response['Code'], bucket_name ) continue else: log.warning( 'S3 Error! Do you have any files ' 'in your S3 bucket?') return {} environments = [(os.path.dirname(k['Key']).split('/', 1))[0] for k in files] environments = set(environments) # pull out the files for the environment for saltenv in environments: # grab only files/dirs that match this saltenv env_files = [k for k in files if k['Key'].startswith(saltenv)] if saltenv not in metadata: metadata[saltenv] = [] found = False for bucket_files in metadata[saltenv]: if bucket_name in bucket_files: bucket_files[bucket_name] += env_files found = True break if not found: metadata[saltenv].append({bucket_name: env_files}) # write the metadata to disk if os.path.isfile(cache_file): os.remove(cache_file) log.debug('Writing buckets cache file') with salt.utils.files.fopen(cache_file, 'w') as fp_: pickle.dump(metadata, fp_) return metadata
python
def _refresh_buckets_cache_file(cache_file): ''' Retrieve the content of all buckets and cache the metadata to the buckets cache file ''' log.debug('Refreshing buckets cache file') key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable = _get_s3_key() metadata = {} # helper s3 query function def __get_s3_meta(bucket, key=key, keyid=keyid): ret, marker = [], '' while True: tmp = __utils__['s3.query'](key=key, keyid=keyid, kms_keyid=keyid, bucket=bucket, service_url=service_url, verify_ssl=verify_ssl, location=location, return_bin=False, path_style=path_style, https_enable=https_enable, params={'marker': marker}) headers = [] for header in tmp: if 'Key' in header: break headers.append(header) ret.extend(tmp) if all([header.get('IsTruncated', 'false') == 'false' for header in headers]): break marker = tmp[-1]['Key'] return ret if _is_env_per_bucket(): # Single environment per bucket for saltenv, buckets in six.iteritems(_get_buckets()): bucket_files_list = [] for bucket_name in buckets: bucket_files = {} s3_meta = __get_s3_meta(bucket_name) # s3 query returned nothing if not s3_meta: continue # grab only the files/dirs bucket_files[bucket_name] = [k for k in s3_meta if 'Key' in k] bucket_files_list.append(bucket_files) # check to see if we added any keys, otherwise investigate possible error conditions if not bucket_files[bucket_name]: meta_response = {} for k in s3_meta: if 'Code' in k or 'Message' in k: # assumes no duplicate keys, consisdent with current erro response. meta_response.update(k) # attempt use of human readable output first. try: log.warning("'%s' response for bucket '%s'", meta_response['Message'], bucket_name) continue except KeyError: # no human readable error message provided if 'Code' in meta_response: log.warning( "'%s' response for bucket '%s'", meta_response['Code'], bucket_name ) continue else: log.warning( 'S3 Error! Do you have any files ' 'in your S3 bucket?') return {} metadata[saltenv] = bucket_files_list else: # Multiple environments per buckets for bucket_name in _get_buckets(): s3_meta = __get_s3_meta(bucket_name) # s3 query returned nothing if not s3_meta: continue # pull out the environment dirs (e.g. the root dirs) files = [k for k in s3_meta if 'Key' in k] # check to see if we added any keys, otherwise investigate possible error conditions if not files: meta_response = {} for k in s3_meta: if 'Code' in k or 'Message' in k: # assumes no duplicate keys, consisdent with current erro response. meta_response.update(k) # attempt use of human readable output first. try: log.warning("'%s' response for bucket '%s'", meta_response['Message'], bucket_name) continue except KeyError: # no human readable error message provided if 'Code' in meta_response: log.warning( "'%s' response for bucket '%s'", meta_response['Code'], bucket_name ) continue else: log.warning( 'S3 Error! Do you have any files ' 'in your S3 bucket?') return {} environments = [(os.path.dirname(k['Key']).split('/', 1))[0] for k in files] environments = set(environments) # pull out the files for the environment for saltenv in environments: # grab only files/dirs that match this saltenv env_files = [k for k in files if k['Key'].startswith(saltenv)] if saltenv not in metadata: metadata[saltenv] = [] found = False for bucket_files in metadata[saltenv]: if bucket_name in bucket_files: bucket_files[bucket_name] += env_files found = True break if not found: metadata[saltenv].append({bucket_name: env_files}) # write the metadata to disk if os.path.isfile(cache_file): os.remove(cache_file) log.debug('Writing buckets cache file') with salt.utils.files.fopen(cache_file, 'w') as fp_: pickle.dump(metadata, fp_) return metadata
[ "def", "_refresh_buckets_cache_file", "(", "cache_file", ")", ":", "log", ".", "debug", "(", "'Refreshing buckets cache file'", ")", "key", ",", "keyid", ",", "service_url", ",", "verify_ssl", ",", "kms_keyid", ",", "location", ",", "path_style", ",", "https_enabl...
Retrieve the content of all buckets and cache the metadata to the buckets cache file
[ "Retrieve", "the", "content", "of", "all", "buckets", "and", "cache", "the", "metadata", "to", "the", "buckets", "cache", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L407-L553
train
saltstack/salt
salt/fileserver/s3fs.py
_read_buckets_cache_file
def _read_buckets_cache_file(cache_file): ''' Return the contents of the buckets cache file ''' log.debug('Reading buckets cache file') with salt.utils.files.fopen(cache_file, 'rb') as fp_: try: data = pickle.load(fp_) except (pickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError, KeyError): data = None return data
python
def _read_buckets_cache_file(cache_file): ''' Return the contents of the buckets cache file ''' log.debug('Reading buckets cache file') with salt.utils.files.fopen(cache_file, 'rb') as fp_: try: data = pickle.load(fp_) except (pickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError, KeyError): data = None return data
[ "def", "_read_buckets_cache_file", "(", "cache_file", ")", ":", "log", ".", "debug", "(", "'Reading buckets cache file'", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "cache_file", ",", "'rb'", ")", "as", "fp_", ":", "try", ":", "dat...
Return the contents of the buckets cache file
[ "Return", "the", "contents", "of", "the", "buckets", "cache", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L556-L570
train
saltstack/salt
salt/fileserver/s3fs.py
_find_files
def _find_files(metadata): ''' Looks for all the files in the S3 bucket cache metadata ''' ret = [] found = {} for bucket_dict in metadata: for bucket_name, data in six.iteritems(bucket_dict): filepaths = [k['Key'] for k in data] filepaths = [k for k in filepaths if not k.endswith('/')] if bucket_name not in found: found[bucket_name] = True ret.append({bucket_name: filepaths}) else: for bucket in ret: if bucket_name in bucket: bucket[bucket_name] += filepaths break return ret
python
def _find_files(metadata): ''' Looks for all the files in the S3 bucket cache metadata ''' ret = [] found = {} for bucket_dict in metadata: for bucket_name, data in six.iteritems(bucket_dict): filepaths = [k['Key'] for k in data] filepaths = [k for k in filepaths if not k.endswith('/')] if bucket_name not in found: found[bucket_name] = True ret.append({bucket_name: filepaths}) else: for bucket in ret: if bucket_name in bucket: bucket[bucket_name] += filepaths break return ret
[ "def", "_find_files", "(", "metadata", ")", ":", "ret", "=", "[", "]", "found", "=", "{", "}", "for", "bucket_dict", "in", "metadata", ":", "for", "bucket_name", ",", "data", "in", "six", ".", "iteritems", "(", "bucket_dict", ")", ":", "filepaths", "="...
Looks for all the files in the S3 bucket cache metadata
[ "Looks", "for", "all", "the", "files", "in", "the", "S3", "bucket", "cache", "metadata" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L573-L593
train
saltstack/salt
salt/fileserver/s3fs.py
_find_dirs
def _find_dirs(metadata): ''' Looks for all the directories in the S3 bucket cache metadata. Supports trailing '/' keys (as created by S3 console) as well as directories discovered in the path of file keys. ''' ret = [] found = {} for bucket_dict in metadata: for bucket_name, data in six.iteritems(bucket_dict): dirpaths = set() for path in [k['Key'] for k in data]: prefix = '' for part in path.split('/')[:-1]: directory = prefix + part + '/' dirpaths.add(directory) prefix = directory if bucket_name not in found: found[bucket_name] = True ret.append({bucket_name: list(dirpaths)}) else: for bucket in ret: if bucket_name in bucket: bucket[bucket_name] += list(dirpaths) bucket[bucket_name] = list(set(bucket[bucket_name])) break return ret
python
def _find_dirs(metadata): ''' Looks for all the directories in the S3 bucket cache metadata. Supports trailing '/' keys (as created by S3 console) as well as directories discovered in the path of file keys. ''' ret = [] found = {} for bucket_dict in metadata: for bucket_name, data in six.iteritems(bucket_dict): dirpaths = set() for path in [k['Key'] for k in data]: prefix = '' for part in path.split('/')[:-1]: directory = prefix + part + '/' dirpaths.add(directory) prefix = directory if bucket_name not in found: found[bucket_name] = True ret.append({bucket_name: list(dirpaths)}) else: for bucket in ret: if bucket_name in bucket: bucket[bucket_name] += list(dirpaths) bucket[bucket_name] = list(set(bucket[bucket_name])) break return ret
[ "def", "_find_dirs", "(", "metadata", ")", ":", "ret", "=", "[", "]", "found", "=", "{", "}", "for", "bucket_dict", "in", "metadata", ":", "for", "bucket_name", ",", "data", "in", "six", ".", "iteritems", "(", "bucket_dict", ")", ":", "dirpaths", "=", ...
Looks for all the directories in the S3 bucket cache metadata. Supports trailing '/' keys (as created by S3 console) as well as directories discovered in the path of file keys.
[ "Looks", "for", "all", "the", "directories", "in", "the", "S3", "bucket", "cache", "metadata", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L596-L625
train
saltstack/salt
salt/fileserver/s3fs.py
_find_file_meta
def _find_file_meta(metadata, bucket_name, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = {} for bucket in env_meta: if bucket_name in bucket: bucket_meta = bucket[bucket_name] files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: try: # Get rid of quotes surrounding md5 item_meta['ETag'] = item_meta['ETag'].strip('"') except KeyError: pass return item_meta
python
def _find_file_meta(metadata, bucket_name, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = {} for bucket in env_meta: if bucket_name in bucket: bucket_meta = bucket[bucket_name] files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: try: # Get rid of quotes surrounding md5 item_meta['ETag'] = item_meta['ETag'].strip('"') except KeyError: pass return item_meta
[ "def", "_find_file_meta", "(", "metadata", ",", "bucket_name", ",", "saltenv", ",", "path", ")", ":", "env_meta", "=", "metadata", "[", "saltenv", "]", "if", "saltenv", "in", "metadata", "else", "{", "}", "bucket_meta", "=", "{", "}", "for", "bucket", "i...
Looks for a file's metadata in the S3 bucket cache file
[ "Looks", "for", "a", "file", "s", "metadata", "in", "the", "S3", "bucket", "cache", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L628-L646
train
saltstack/salt
salt/fileserver/s3fs.py
_get_file_from_s3
def _get_file_from_s3(metadata, saltenv, bucket_name, path, cached_file_path): ''' Checks the local cache for the file, if it's old or missing go grab the file from S3 and update the cache ''' key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable = _get_s3_key() # check the local cache... if os.path.isfile(cached_file_path): file_meta = _find_file_meta(metadata, bucket_name, saltenv, path) if file_meta: file_etag = file_meta['ETag'] if file_etag.find('-') == -1: file_md5 = file_etag cached_md5 = salt.utils.hashutils.get_hash(cached_file_path, 'md5') # hashes match we have a cache hit if cached_md5 == file_md5: return else: cached_file_stat = os.stat(cached_file_path) cached_file_size = cached_file_stat.st_size cached_file_mtime = datetime.datetime.fromtimestamp( cached_file_stat.st_mtime) cached_file_lastmod = datetime.datetime.strptime( file_meta['LastModified'], '%Y-%m-%dT%H:%M:%S.%fZ') if (cached_file_size == int(file_meta['Size']) and cached_file_mtime > cached_file_lastmod): log.debug('cached file size equal to metadata size and ' 'cached file mtime later than metadata last ' 'modification time.') ret = __utils__['s3.query']( key=key, keyid=keyid, kms_keyid=keyid, method='HEAD', bucket=bucket_name, service_url=service_url, verify_ssl=verify_ssl, location=location, path=_quote(path), local_file=cached_file_path, full_headers=True, path_style=path_style, https_enable=https_enable ) if ret is not None: for header_name, header_value in ret['headers'].items(): name = header_name.strip() value = header_value.strip() if six.text_type(name).lower() == 'last-modified': s3_file_mtime = datetime.datetime.strptime( value, '%a, %d %b %Y %H:%M:%S %Z') elif six.text_type(name).lower() == 'content-length': s3_file_size = int(value) if (cached_file_size == s3_file_size and cached_file_mtime > s3_file_mtime): log.info( '%s - %s : %s skipped download since cached file size ' 'equal to and mtime after s3 values', bucket_name, saltenv, path ) return # ... or get the file from S3 __utils__['s3.query']( key=key, keyid=keyid, kms_keyid=keyid, bucket=bucket_name, service_url=service_url, verify_ssl=verify_ssl, location=location, path=_quote(path), local_file=cached_file_path, path_style=path_style, https_enable=https_enable, )
python
def _get_file_from_s3(metadata, saltenv, bucket_name, path, cached_file_path): ''' Checks the local cache for the file, if it's old or missing go grab the file from S3 and update the cache ''' key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable = _get_s3_key() # check the local cache... if os.path.isfile(cached_file_path): file_meta = _find_file_meta(metadata, bucket_name, saltenv, path) if file_meta: file_etag = file_meta['ETag'] if file_etag.find('-') == -1: file_md5 = file_etag cached_md5 = salt.utils.hashutils.get_hash(cached_file_path, 'md5') # hashes match we have a cache hit if cached_md5 == file_md5: return else: cached_file_stat = os.stat(cached_file_path) cached_file_size = cached_file_stat.st_size cached_file_mtime = datetime.datetime.fromtimestamp( cached_file_stat.st_mtime) cached_file_lastmod = datetime.datetime.strptime( file_meta['LastModified'], '%Y-%m-%dT%H:%M:%S.%fZ') if (cached_file_size == int(file_meta['Size']) and cached_file_mtime > cached_file_lastmod): log.debug('cached file size equal to metadata size and ' 'cached file mtime later than metadata last ' 'modification time.') ret = __utils__['s3.query']( key=key, keyid=keyid, kms_keyid=keyid, method='HEAD', bucket=bucket_name, service_url=service_url, verify_ssl=verify_ssl, location=location, path=_quote(path), local_file=cached_file_path, full_headers=True, path_style=path_style, https_enable=https_enable ) if ret is not None: for header_name, header_value in ret['headers'].items(): name = header_name.strip() value = header_value.strip() if six.text_type(name).lower() == 'last-modified': s3_file_mtime = datetime.datetime.strptime( value, '%a, %d %b %Y %H:%M:%S %Z') elif six.text_type(name).lower() == 'content-length': s3_file_size = int(value) if (cached_file_size == s3_file_size and cached_file_mtime > s3_file_mtime): log.info( '%s - %s : %s skipped download since cached file size ' 'equal to and mtime after s3 values', bucket_name, saltenv, path ) return # ... or get the file from S3 __utils__['s3.query']( key=key, keyid=keyid, kms_keyid=keyid, bucket=bucket_name, service_url=service_url, verify_ssl=verify_ssl, location=location, path=_quote(path), local_file=cached_file_path, path_style=path_style, https_enable=https_enable, )
[ "def", "_get_file_from_s3", "(", "metadata", ",", "saltenv", ",", "bucket_name", ",", "path", ",", "cached_file_path", ")", ":", "key", ",", "keyid", ",", "service_url", ",", "verify_ssl", ",", "kms_keyid", ",", "location", ",", "path_style", ",", "https_enabl...
Checks the local cache for the file, if it's old or missing go grab the file from S3 and update the cache
[ "Checks", "the", "local", "cache", "for", "the", "file", "if", "it", "s", "old", "or", "missing", "go", "grab", "the", "file", "from", "S3", "and", "update", "the", "cache" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L657-L736
train
saltstack/salt
salt/fileserver/s3fs.py
_trim_env_off_path
def _trim_env_off_path(paths, saltenv, trim_slash=False): ''' Return a list of file paths with the saltenv directory removed ''' env_len = None if _is_env_per_bucket() else len(saltenv) + 1 slash_len = -1 if trim_slash else None return [d[env_len:slash_len] for d in paths]
python
def _trim_env_off_path(paths, saltenv, trim_slash=False): ''' Return a list of file paths with the saltenv directory removed ''' env_len = None if _is_env_per_bucket() else len(saltenv) + 1 slash_len = -1 if trim_slash else None return [d[env_len:slash_len] for d in paths]
[ "def", "_trim_env_off_path", "(", "paths", ",", "saltenv", ",", "trim_slash", "=", "False", ")", ":", "env_len", "=", "None", "if", "_is_env_per_bucket", "(", ")", "else", "len", "(", "saltenv", ")", "+", "1", "slash_len", "=", "-", "1", "if", "trim_slas...
Return a list of file paths with the saltenv directory removed
[ "Return", "a", "list", "of", "file", "paths", "with", "the", "saltenv", "directory", "removed" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L739-L746
train
saltstack/salt
salt/fileserver/s3fs.py
_is_env_per_bucket
def _is_env_per_bucket(): ''' Return the configuration mode, either buckets per environment or a list of buckets that have environment dirs in their root ''' buckets = _get_buckets() if isinstance(buckets, dict): return True elif isinstance(buckets, list): return False else: raise ValueError('Incorrect s3.buckets type given in config')
python
def _is_env_per_bucket(): ''' Return the configuration mode, either buckets per environment or a list of buckets that have environment dirs in their root ''' buckets = _get_buckets() if isinstance(buckets, dict): return True elif isinstance(buckets, list): return False else: raise ValueError('Incorrect s3.buckets type given in config')
[ "def", "_is_env_per_bucket", "(", ")", ":", "buckets", "=", "_get_buckets", "(", ")", "if", "isinstance", "(", "buckets", ",", "dict", ")", ":", "return", "True", "elif", "isinstance", "(", "buckets", ",", "list", ")", ":", "return", "False", "else", ":"...
Return the configuration mode, either buckets per environment or a list of buckets that have environment dirs in their root
[ "Return", "the", "configuration", "mode", "either", "buckets", "per", "environment", "or", "a", "list", "of", "buckets", "that", "have", "environment", "dirs", "in", "their", "root" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L749-L761
train
saltstack/salt
salt/modules/boto3_route53.py
find_hosted_zone
def find_hosted_zone(Id=None, Name=None, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Find a hosted zone with the given characteristics. Id The unique Zone Identifier for the Hosted Zone. Exclusive with Name. Name The domain name associated with the Hosted Zone. Exclusive with Id. Note this has the potential to match more then one hosted zone (e.g. a public and a private if both exist) which will raise an error unless PrivateZone has also been passed in order split the different. PrivateZone Boolean - Set to True if searching for a private hosted zone. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.find_hosted_zone Name=salt.org. \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' if not _exactly_one((Id, Name)): raise SaltInvocationError('Exactly one of either Id or Name is required.') if PrivateZone is not None and not isinstance(PrivateZone, bool): raise SaltInvocationError('If set, PrivateZone must be a bool (e.g. True / False).') if Id: ret = get_hosted_zone(Id, region=region, key=key, keyid=keyid, profile=profile) else: ret = get_hosted_zones_by_domain(Name, region=region, key=key, keyid=keyid, profile=profile) if PrivateZone is not None: ret = [m for m in ret if m['HostedZone']['Config']['PrivateZone'] is PrivateZone] if len(ret) > 1: log.error( 'Request matched more than one Hosted Zone (%s). Refine your ' 'criteria and try again.', [z['HostedZone']['Id'] for z in ret] ) ret = [] return ret
python
def find_hosted_zone(Id=None, Name=None, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Find a hosted zone with the given characteristics. Id The unique Zone Identifier for the Hosted Zone. Exclusive with Name. Name The domain name associated with the Hosted Zone. Exclusive with Id. Note this has the potential to match more then one hosted zone (e.g. a public and a private if both exist) which will raise an error unless PrivateZone has also been passed in order split the different. PrivateZone Boolean - Set to True if searching for a private hosted zone. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.find_hosted_zone Name=salt.org. \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' if not _exactly_one((Id, Name)): raise SaltInvocationError('Exactly one of either Id or Name is required.') if PrivateZone is not None and not isinstance(PrivateZone, bool): raise SaltInvocationError('If set, PrivateZone must be a bool (e.g. True / False).') if Id: ret = get_hosted_zone(Id, region=region, key=key, keyid=keyid, profile=profile) else: ret = get_hosted_zones_by_domain(Name, region=region, key=key, keyid=keyid, profile=profile) if PrivateZone is not None: ret = [m for m in ret if m['HostedZone']['Config']['PrivateZone'] is PrivateZone] if len(ret) > 1: log.error( 'Request matched more than one Hosted Zone (%s). Refine your ' 'criteria and try again.', [z['HostedZone']['Id'] for z in ret] ) ret = [] return ret
[ "def", "find_hosted_zone", "(", "Id", "=", "None", ",", "Name", "=", "None", ",", "PrivateZone", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "_exac...
Find a hosted zone with the given characteristics. Id The unique Zone Identifier for the Hosted Zone. Exclusive with Name. Name The domain name associated with the Hosted Zone. Exclusive with Id. Note this has the potential to match more then one hosted zone (e.g. a public and a private if both exist) which will raise an error unless PrivateZone has also been passed in order split the different. PrivateZone Boolean - Set to True if searching for a private hosted zone. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.find_hosted_zone Name=salt.org. \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}'
[ "Find", "a", "hosted", "zone", "with", "the", "given", "characteristics", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L132-L184
train
saltstack/salt
salt/modules/boto3_route53.py
get_hosted_zone
def get_hosted_zone(Id, region=None, key=None, keyid=None, profile=None): ''' Return detailed info about the given zone. Id The unique Zone Identifier for the Hosted Zone. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.get_hosted_zone Z1234567690 \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {'Id': Id} return _collect_results(conn.get_hosted_zone, None, args)
python
def get_hosted_zone(Id, region=None, key=None, keyid=None, profile=None): ''' Return detailed info about the given zone. Id The unique Zone Identifier for the Hosted Zone. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.get_hosted_zone Z1234567690 \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {'Id': Id} return _collect_results(conn.get_hosted_zone, None, args)
[ "def", "get_hosted_zone", "(", "Id", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid"...
Return detailed info about the given zone. Id The unique Zone Identifier for the Hosted Zone. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.get_hosted_zone Z1234567690 \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}'
[ "Return", "detailed", "info", "about", "the", "given", "zone", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L187-L215
train
saltstack/salt
salt/modules/boto3_route53.py
get_hosted_zones_by_domain
def get_hosted_zones_by_domain(Name, region=None, key=None, keyid=None, profile=None): ''' Find any zones with the given domain name and return detailed info about them. Note that this can return multiple Route53 zones, since a domain name can be used in both public and private zones. Name The domain name associated with the Hosted Zone(s). region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.get_hosted_zones_by_domain salt.org. \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) zones = [z for z in _collect_results(conn.list_hosted_zones, 'HostedZones', {}) if z['Name'] == aws_encode(Name)] ret = [] for z in zones: ret += get_hosted_zone(Id=z['Id'], region=region, key=key, keyid=keyid, profile=profile) return ret
python
def get_hosted_zones_by_domain(Name, region=None, key=None, keyid=None, profile=None): ''' Find any zones with the given domain name and return detailed info about them. Note that this can return multiple Route53 zones, since a domain name can be used in both public and private zones. Name The domain name associated with the Hosted Zone(s). region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.get_hosted_zones_by_domain salt.org. \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) zones = [z for z in _collect_results(conn.list_hosted_zones, 'HostedZones', {}) if z['Name'] == aws_encode(Name)] ret = [] for z in zones: ret += get_hosted_zone(Id=z['Id'], region=region, key=key, keyid=keyid, profile=profile) return ret
[ "def", "get_hosted_zones_by_domain", "(", "Name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", "...
Find any zones with the given domain name and return detailed info about them. Note that this can return multiple Route53 zones, since a domain name can be used in both public and private zones. Name The domain name associated with the Hosted Zone(s). region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.get_hosted_zones_by_domain salt.org. \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}'
[ "Find", "any", "zones", "with", "the", "given", "domain", "name", "and", "return", "detailed", "info", "about", "them", ".", "Note", "that", "this", "can", "return", "multiple", "Route53", "zones", "since", "a", "domain", "name", "can", "be", "used", "in",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L218-L252
train
saltstack/salt
salt/modules/boto3_route53.py
list_hosted_zones
def list_hosted_zones(DelegationSetId=None, region=None, key=None, keyid=None, profile=None): ''' Return detailed info about all zones in the bound account. DelegationSetId If you're using reusable delegation sets and you want to list all of the hosted zones that are associated with a reusable delegation set, specify the ID of that delegation set. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.describe_hosted_zones \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {'DelegationSetId': DelegationSetId} if DelegationSetId else {} return _collect_results(conn.list_hosted_zones, 'HostedZones', args)
python
def list_hosted_zones(DelegationSetId=None, region=None, key=None, keyid=None, profile=None): ''' Return detailed info about all zones in the bound account. DelegationSetId If you're using reusable delegation sets and you want to list all of the hosted zones that are associated with a reusable delegation set, specify the ID of that delegation set. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.describe_hosted_zones \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {'DelegationSetId': DelegationSetId} if DelegationSetId else {} return _collect_results(conn.list_hosted_zones, 'HostedZones', args)
[ "def", "list_hosted_zones", "(", "DelegationSetId", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", ...
Return detailed info about all zones in the bound account. DelegationSetId If you're using reusable delegation sets and you want to list all of the hosted zones that are associated with a reusable delegation set, specify the ID of that delegation set. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. code-block:: bash salt myminion boto3_route53.describe_hosted_zones \ profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}'
[ "Return", "detailed", "info", "about", "all", "zones", "in", "the", "bound", "account", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L255-L284
train
saltstack/salt
salt/modules/boto3_route53.py
create_hosted_zone
def create_hosted_zone(Name, VPCId=None, VPCName=None, VPCRegion=None, CallerReference=None, Comment='', PrivateZone=False, DelegationSetId=None, region=None, key=None, keyid=None, profile=None): ''' Create a new Route53 Hosted Zone. Returns a Python data structure with information about the newly created Hosted Zone. Name The name of the domain. This should be a fully-specified domain, and should terminate with a period. This is the name you have registered with your DNS registrar. It is also the name you will delegate from your registrar to the Amazon Route 53 delegation servers returned in response to this request. VPCId When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCName. Ignored if passed for a non-private zone. VPCName When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCId. Ignored if passed for a non-private zone. VPCRegion When creating a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from VPCId or VPCName, if possible. If this fails, you'll need to provide an explicit value for this option. Ignored if passed for a non-private zone. CallerReference A unique string that identifies the request and that allows create_hosted_zone() calls to be retried without the risk of executing the operation twice. This is a required parameter when creating new Hosted Zones. Maximum length of 128. Comment Any comments you want to include about the hosted zone. PrivateZone Boolean - Set to True if creating a private hosted zone. DelegationSetId If you want to associate a reusable delegation set with this hosted zone, the ID that Amazon Route 53 assigned to the reusable delegation set when you created it. Note that XXX TODO create_delegation_set() is not yet implemented, so you'd need to manually create any delegation sets before utilizing this. region Region endpoint to connect to. key AWS key to bind with. keyid AWS keyid to bind with. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example:: salt myminion boto3_route53.create_hosted_zone example.org. ''' if not Name.endswith('.'): raise SaltInvocationError('Domain must be fully-qualified, complete with trailing period.') Name = aws_encode(Name) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deets = find_hosted_zone(Name=Name, PrivateZone=PrivateZone, region=region, key=key, keyid=keyid, profile=profile) if deets: log.info( 'Route 53 hosted zone %s already exists. You may want to pass ' 'e.g. \'PrivateZone=True\' or similar...', Name ) return None args = { 'Name': Name, 'CallerReference': CallerReference, 'HostedZoneConfig': { 'Comment': Comment, 'PrivateZone': PrivateZone } } args.update({'DelegationSetId': DelegationSetId}) if DelegationSetId else None if PrivateZone: if not _exactly_one((VPCName, VPCId)): raise SaltInvocationError('Either VPCName or VPCId is required when creating a ' 'private zone.') vpcs = __salt__['boto_vpc.describe_vpcs']( vpc_id=VPCId, name=VPCName, region=region, key=key, keyid=keyid, profile=profile).get('vpcs', []) if VPCRegion and vpcs: vpcs = [v for v in vpcs if v['region'] == VPCRegion] if not vpcs: log.error('Private zone requested but no VPC matching given criteria found.') return None if len(vpcs) > 1: log.error( 'Private zone requested but multiple VPCs matching given ' 'criteria found: %s.', [v['id'] for v in vpcs] ) return None vpc = vpcs[0] if VPCName: VPCId = vpc['id'] if not VPCRegion: VPCRegion = vpc['region'] args.update({'VPC': {'VPCId': VPCId, 'VPCRegion': VPCRegion}}) else: if any((VPCId, VPCName, VPCRegion)): log.info('Options VPCId, VPCName, and VPCRegion are ignored when creating ' 'non-private zones.') tries = 10 while tries: try: r = conn.create_hosted_zone(**args) r.pop('ResponseMetadata', None) if _wait_for_sync(r['ChangeInfo']['Id'], conn): return [r] return [] except ClientError as e: if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to create hosted zone %s: %s', Name, e) return [] return []
python
def create_hosted_zone(Name, VPCId=None, VPCName=None, VPCRegion=None, CallerReference=None, Comment='', PrivateZone=False, DelegationSetId=None, region=None, key=None, keyid=None, profile=None): ''' Create a new Route53 Hosted Zone. Returns a Python data structure with information about the newly created Hosted Zone. Name The name of the domain. This should be a fully-specified domain, and should terminate with a period. This is the name you have registered with your DNS registrar. It is also the name you will delegate from your registrar to the Amazon Route 53 delegation servers returned in response to this request. VPCId When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCName. Ignored if passed for a non-private zone. VPCName When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCId. Ignored if passed for a non-private zone. VPCRegion When creating a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from VPCId or VPCName, if possible. If this fails, you'll need to provide an explicit value for this option. Ignored if passed for a non-private zone. CallerReference A unique string that identifies the request and that allows create_hosted_zone() calls to be retried without the risk of executing the operation twice. This is a required parameter when creating new Hosted Zones. Maximum length of 128. Comment Any comments you want to include about the hosted zone. PrivateZone Boolean - Set to True if creating a private hosted zone. DelegationSetId If you want to associate a reusable delegation set with this hosted zone, the ID that Amazon Route 53 assigned to the reusable delegation set when you created it. Note that XXX TODO create_delegation_set() is not yet implemented, so you'd need to manually create any delegation sets before utilizing this. region Region endpoint to connect to. key AWS key to bind with. keyid AWS keyid to bind with. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example:: salt myminion boto3_route53.create_hosted_zone example.org. ''' if not Name.endswith('.'): raise SaltInvocationError('Domain must be fully-qualified, complete with trailing period.') Name = aws_encode(Name) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deets = find_hosted_zone(Name=Name, PrivateZone=PrivateZone, region=region, key=key, keyid=keyid, profile=profile) if deets: log.info( 'Route 53 hosted zone %s already exists. You may want to pass ' 'e.g. \'PrivateZone=True\' or similar...', Name ) return None args = { 'Name': Name, 'CallerReference': CallerReference, 'HostedZoneConfig': { 'Comment': Comment, 'PrivateZone': PrivateZone } } args.update({'DelegationSetId': DelegationSetId}) if DelegationSetId else None if PrivateZone: if not _exactly_one((VPCName, VPCId)): raise SaltInvocationError('Either VPCName or VPCId is required when creating a ' 'private zone.') vpcs = __salt__['boto_vpc.describe_vpcs']( vpc_id=VPCId, name=VPCName, region=region, key=key, keyid=keyid, profile=profile).get('vpcs', []) if VPCRegion and vpcs: vpcs = [v for v in vpcs if v['region'] == VPCRegion] if not vpcs: log.error('Private zone requested but no VPC matching given criteria found.') return None if len(vpcs) > 1: log.error( 'Private zone requested but multiple VPCs matching given ' 'criteria found: %s.', [v['id'] for v in vpcs] ) return None vpc = vpcs[0] if VPCName: VPCId = vpc['id'] if not VPCRegion: VPCRegion = vpc['region'] args.update({'VPC': {'VPCId': VPCId, 'VPCRegion': VPCRegion}}) else: if any((VPCId, VPCName, VPCRegion)): log.info('Options VPCId, VPCName, and VPCRegion are ignored when creating ' 'non-private zones.') tries = 10 while tries: try: r = conn.create_hosted_zone(**args) r.pop('ResponseMetadata', None) if _wait_for_sync(r['ChangeInfo']['Id'], conn): return [r] return [] except ClientError as e: if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to create hosted zone %s: %s', Name, e) return [] return []
[ "def", "create_hosted_zone", "(", "Name", ",", "VPCId", "=", "None", ",", "VPCName", "=", "None", ",", "VPCRegion", "=", "None", ",", "CallerReference", "=", "None", ",", "Comment", "=", "''", ",", "PrivateZone", "=", "False", ",", "DelegationSetId", "=", ...
Create a new Route53 Hosted Zone. Returns a Python data structure with information about the newly created Hosted Zone. Name The name of the domain. This should be a fully-specified domain, and should terminate with a period. This is the name you have registered with your DNS registrar. It is also the name you will delegate from your registrar to the Amazon Route 53 delegation servers returned in response to this request. VPCId When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCName. Ignored if passed for a non-private zone. VPCName When creating a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCId. Ignored if passed for a non-private zone. VPCRegion When creating a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from VPCId or VPCName, if possible. If this fails, you'll need to provide an explicit value for this option. Ignored if passed for a non-private zone. CallerReference A unique string that identifies the request and that allows create_hosted_zone() calls to be retried without the risk of executing the operation twice. This is a required parameter when creating new Hosted Zones. Maximum length of 128. Comment Any comments you want to include about the hosted zone. PrivateZone Boolean - Set to True if creating a private hosted zone. DelegationSetId If you want to associate a reusable delegation set with this hosted zone, the ID that Amazon Route 53 assigned to the reusable delegation set when you created it. Note that XXX TODO create_delegation_set() is not yet implemented, so you'd need to manually create any delegation sets before utilizing this. region Region endpoint to connect to. key AWS key to bind with. keyid AWS keyid to bind with. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example:: salt myminion boto3_route53.create_hosted_zone example.org.
[ "Create", "a", "new", "Route53", "Hosted", "Zone", ".", "Returns", "a", "Python", "data", "structure", "with", "information", "about", "the", "newly", "created", "Hosted", "Zone", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L287-L412
train
saltstack/salt
salt/modules/boto3_route53.py
update_hosted_zone_comment
def update_hosted_zone_comment(Id=None, Name=None, Comment=None, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Update the comment on an existing Route 53 hosted zone. Id The unique Zone Identifier for the Hosted Zone. Name The domain name associated with the Hosted Zone(s). Comment Any comments you want to include about the hosted zone. PrivateZone Boolean - Set to True if changing a private hosted zone. CLI Example:: salt myminion boto3_route53.update_hosted_zone_comment Name=example.org. \ Comment="This is an example comment for an example zone" ''' if not _exactly_one((Id, Name)): raise SaltInvocationError('Exactly one of either Id or Name is required.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if Name: args = {'Name': Name, 'PrivateZone': PrivateZone, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return [] Id = zone[0]['HostedZone']['Id'] tries = 10 while tries: try: r = conn.update_hosted_zone_comment(Id=Id, Comment=Comment) r.pop('ResponseMetadata', None) return [r] except ClientError as e: if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to update comment on hosted zone %s: %s', Name or Id, e) return []
python
def update_hosted_zone_comment(Id=None, Name=None, Comment=None, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Update the comment on an existing Route 53 hosted zone. Id The unique Zone Identifier for the Hosted Zone. Name The domain name associated with the Hosted Zone(s). Comment Any comments you want to include about the hosted zone. PrivateZone Boolean - Set to True if changing a private hosted zone. CLI Example:: salt myminion boto3_route53.update_hosted_zone_comment Name=example.org. \ Comment="This is an example comment for an example zone" ''' if not _exactly_one((Id, Name)): raise SaltInvocationError('Exactly one of either Id or Name is required.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if Name: args = {'Name': Name, 'PrivateZone': PrivateZone, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return [] Id = zone[0]['HostedZone']['Id'] tries = 10 while tries: try: r = conn.update_hosted_zone_comment(Id=Id, Comment=Comment) r.pop('ResponseMetadata', None) return [r] except ClientError as e: if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to update comment on hosted zone %s: %s', Name or Id, e) return []
[ "def", "update_hosted_zone_comment", "(", "Id", "=", "None", ",", "Name", "=", "None", ",", "Comment", "=", "None", ",", "PrivateZone", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", ...
Update the comment on an existing Route 53 hosted zone. Id The unique Zone Identifier for the Hosted Zone. Name The domain name associated with the Hosted Zone(s). Comment Any comments you want to include about the hosted zone. PrivateZone Boolean - Set to True if changing a private hosted zone. CLI Example:: salt myminion boto3_route53.update_hosted_zone_comment Name=example.org. \ Comment="This is an example comment for an example zone"
[ "Update", "the", "comment", "on", "an", "existing", "Route", "53", "hosted", "zone", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L415-L462
train
saltstack/salt
salt/modules/boto3_route53.py
associate_vpc_with_hosted_zone
def associate_vpc_with_hosted_zone(HostedZoneId=None, Name=None, VPCId=None, VPCName=None, VPCRegion=None, Comment=None, region=None, key=None, keyid=None, profile=None): ''' Associates an Amazon VPC with a private hosted zone. To perform the association, the VPC and the private hosted zone must already exist. You can't convert a public hosted zone into a private hosted zone. If you want to associate a VPC from one AWS account with a zone from a another, the AWS account owning the hosted zone must first submit a CreateVPCAssociationAuthorization (using create_vpc_association_authorization() or by other means, such as the AWS console). With that done, the account owning the VPC can then call associate_vpc_with_hosted_zone() to create the association. Note that if both sides happen to be within the same account, associate_vpc_with_hosted_zone() is enough on its own, and there is no need for the CreateVPCAssociationAuthorization step. Also note that looking up hosted zones by name (e.g. using the Name parameter) only works within a single account - if you're associating a VPC to a zone in a different account, as outlined above, you unfortunately MUST use the HostedZoneId parameter exclusively. HostedZoneId The unique Zone Identifier for the Hosted Zone. Name The domain name associated with the Hosted Zone(s). VPCId When working with a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCName. VPCName When working with a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCId. VPCRegion When working with a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from VPCId or VPCName, if possible. If this fails, you'll need to provide an explicit value for VPCRegion. Comment Any comments you want to include about the change being made. CLI Example:: salt myminion boto3_route53.associate_vpc_with_hosted_zone \ Name=example.org. VPCName=myVPC \ VPCRegion=us-east-1 Comment="Whoo-hoo! I added another VPC." ''' if not _exactly_one((HostedZoneId, Name)): raise SaltInvocationError('Exactly one of either HostedZoneId or Name is required.') if not _exactly_one((VPCId, VPCName)): raise SaltInvocationError('Exactly one of either VPCId or VPCName is required.') if Name: # {'PrivateZone': True} because you can only associate VPCs with private hosted zones. args = {'Name': Name, 'PrivateZone': True, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} zone = find_hosted_zone(**args) if not zone: log.error( "Couldn't resolve domain name %s to a private hosted zone ID.", Name ) return False HostedZoneId = zone[0]['HostedZone']['Id'] vpcs = __salt__['boto_vpc.describe_vpcs'](vpc_id=VPCId, name=VPCName, region=region, key=key, keyid=keyid, profile=profile).get('vpcs', []) if VPCRegion and vpcs: vpcs = [v for v in vpcs if v['region'] == VPCRegion] if not vpcs: log.error('No VPC matching the given criteria found.') return False if len(vpcs) > 1: log.error('Multiple VPCs matching the given criteria found: %s.', ', '.join([v['id'] for v in vpcs])) return False vpc = vpcs[0] if VPCName: VPCId = vpc['id'] if not VPCRegion: VPCRegion = vpc['region'] args = {'HostedZoneId': HostedZoneId, 'VPC': {'VPCId': VPCId, 'VPCRegion': VPCRegion}} args.update({'Comment': Comment}) if Comment is not None else None conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) tries = 10 while tries: try: r = conn.associate_vpc_with_hosted_zone(**args) return _wait_for_sync(r['ChangeInfo']['Id'], conn) except ClientError as e: if e.response.get('Error', {}).get('Code') == 'ConflictingDomainExists': log.debug('VPC Association already exists.') # return True since the current state is the desired one return True if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to associate VPC %s with hosted zone %s: %s', VPCName or VPCId, Name or HostedZoneId, e) return False
python
def associate_vpc_with_hosted_zone(HostedZoneId=None, Name=None, VPCId=None, VPCName=None, VPCRegion=None, Comment=None, region=None, key=None, keyid=None, profile=None): ''' Associates an Amazon VPC with a private hosted zone. To perform the association, the VPC and the private hosted zone must already exist. You can't convert a public hosted zone into a private hosted zone. If you want to associate a VPC from one AWS account with a zone from a another, the AWS account owning the hosted zone must first submit a CreateVPCAssociationAuthorization (using create_vpc_association_authorization() or by other means, such as the AWS console). With that done, the account owning the VPC can then call associate_vpc_with_hosted_zone() to create the association. Note that if both sides happen to be within the same account, associate_vpc_with_hosted_zone() is enough on its own, and there is no need for the CreateVPCAssociationAuthorization step. Also note that looking up hosted zones by name (e.g. using the Name parameter) only works within a single account - if you're associating a VPC to a zone in a different account, as outlined above, you unfortunately MUST use the HostedZoneId parameter exclusively. HostedZoneId The unique Zone Identifier for the Hosted Zone. Name The domain name associated with the Hosted Zone(s). VPCId When working with a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCName. VPCName When working with a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCId. VPCRegion When working with a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from VPCId or VPCName, if possible. If this fails, you'll need to provide an explicit value for VPCRegion. Comment Any comments you want to include about the change being made. CLI Example:: salt myminion boto3_route53.associate_vpc_with_hosted_zone \ Name=example.org. VPCName=myVPC \ VPCRegion=us-east-1 Comment="Whoo-hoo! I added another VPC." ''' if not _exactly_one((HostedZoneId, Name)): raise SaltInvocationError('Exactly one of either HostedZoneId or Name is required.') if not _exactly_one((VPCId, VPCName)): raise SaltInvocationError('Exactly one of either VPCId or VPCName is required.') if Name: # {'PrivateZone': True} because you can only associate VPCs with private hosted zones. args = {'Name': Name, 'PrivateZone': True, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} zone = find_hosted_zone(**args) if not zone: log.error( "Couldn't resolve domain name %s to a private hosted zone ID.", Name ) return False HostedZoneId = zone[0]['HostedZone']['Id'] vpcs = __salt__['boto_vpc.describe_vpcs'](vpc_id=VPCId, name=VPCName, region=region, key=key, keyid=keyid, profile=profile).get('vpcs', []) if VPCRegion and vpcs: vpcs = [v for v in vpcs if v['region'] == VPCRegion] if not vpcs: log.error('No VPC matching the given criteria found.') return False if len(vpcs) > 1: log.error('Multiple VPCs matching the given criteria found: %s.', ', '.join([v['id'] for v in vpcs])) return False vpc = vpcs[0] if VPCName: VPCId = vpc['id'] if not VPCRegion: VPCRegion = vpc['region'] args = {'HostedZoneId': HostedZoneId, 'VPC': {'VPCId': VPCId, 'VPCRegion': VPCRegion}} args.update({'Comment': Comment}) if Comment is not None else None conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) tries = 10 while tries: try: r = conn.associate_vpc_with_hosted_zone(**args) return _wait_for_sync(r['ChangeInfo']['Id'], conn) except ClientError as e: if e.response.get('Error', {}).get('Code') == 'ConflictingDomainExists': log.debug('VPC Association already exists.') # return True since the current state is the desired one return True if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to associate VPC %s with hosted zone %s: %s', VPCName or VPCId, Name or HostedZoneId, e) return False
[ "def", "associate_vpc_with_hosted_zone", "(", "HostedZoneId", "=", "None", ",", "Name", "=", "None", ",", "VPCId", "=", "None", ",", "VPCName", "=", "None", ",", "VPCRegion", "=", "None", ",", "Comment", "=", "None", ",", "region", "=", "None", ",", "key...
Associates an Amazon VPC with a private hosted zone. To perform the association, the VPC and the private hosted zone must already exist. You can't convert a public hosted zone into a private hosted zone. If you want to associate a VPC from one AWS account with a zone from a another, the AWS account owning the hosted zone must first submit a CreateVPCAssociationAuthorization (using create_vpc_association_authorization() or by other means, such as the AWS console). With that done, the account owning the VPC can then call associate_vpc_with_hosted_zone() to create the association. Note that if both sides happen to be within the same account, associate_vpc_with_hosted_zone() is enough on its own, and there is no need for the CreateVPCAssociationAuthorization step. Also note that looking up hosted zones by name (e.g. using the Name parameter) only works within a single account - if you're associating a VPC to a zone in a different account, as outlined above, you unfortunately MUST use the HostedZoneId parameter exclusively. HostedZoneId The unique Zone Identifier for the Hosted Zone. Name The domain name associated with the Hosted Zone(s). VPCId When working with a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCName. VPCName When working with a private hosted zone, either the VPC ID or VPC Name to associate with is required. Exclusive with VPCId. VPCRegion When working with a private hosted zone, the region of the associated VPC is required. If not provided, an effort will be made to determine it from VPCId or VPCName, if possible. If this fails, you'll need to provide an explicit value for VPCRegion. Comment Any comments you want to include about the change being made. CLI Example:: salt myminion boto3_route53.associate_vpc_with_hosted_zone \ Name=example.org. VPCName=myVPC \ VPCRegion=us-east-1 Comment="Whoo-hoo! I added another VPC."
[ "Associates", "an", "Amazon", "VPC", "with", "a", "private", "hosted", "zone", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L465-L567
train
saltstack/salt
salt/modules/boto3_route53.py
delete_hosted_zone
def delete_hosted_zone(Id, region=None, key=None, keyid=None, profile=None): ''' Delete a Route53 hosted zone. CLI Example:: salt myminion boto3_route53.delete_hosted_zone Z1234567890 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: r = conn.delete_hosted_zone(Id=Id) return _wait_for_sync(r['ChangeInfo']['Id'], conn) except ClientError as e: log.error('Failed to delete hosted zone %s: %s', Id, e) return False
python
def delete_hosted_zone(Id, region=None, key=None, keyid=None, profile=None): ''' Delete a Route53 hosted zone. CLI Example:: salt myminion boto3_route53.delete_hosted_zone Z1234567890 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: r = conn.delete_hosted_zone(Id=Id) return _wait_for_sync(r['ChangeInfo']['Id'], conn) except ClientError as e: log.error('Failed to delete hosted zone %s: %s', Id, e) return False
[ "def", "delete_hosted_zone", "(", "Id", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "key...
Delete a Route53 hosted zone. CLI Example:: salt myminion boto3_route53.delete_hosted_zone Z1234567890
[ "Delete", "a", "Route53", "hosted", "zone", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L686-L700
train
saltstack/salt
salt/modules/boto3_route53.py
delete_hosted_zone_by_domain
def delete_hosted_zone_by_domain(Name, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Delete a Route53 hosted zone by domain name, and PrivateZone status if provided. CLI Example:: salt myminion boto3_route53.delete_hosted_zone_by_domain example.org. ''' args = {'Name': Name, 'PrivateZone': PrivateZone, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} # Be extra pedantic in the service of safety - if public/private is not provided and the domain # name resolves to both, fail and require them to declare it explicitly. zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return False Id = zone[0]['HostedZone']['Id'] return delete_hosted_zone(Id=Id, region=region, key=key, keyid=keyid, profile=profile)
python
def delete_hosted_zone_by_domain(Name, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Delete a Route53 hosted zone by domain name, and PrivateZone status if provided. CLI Example:: salt myminion boto3_route53.delete_hosted_zone_by_domain example.org. ''' args = {'Name': Name, 'PrivateZone': PrivateZone, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} # Be extra pedantic in the service of safety - if public/private is not provided and the domain # name resolves to both, fail and require them to declare it explicitly. zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return False Id = zone[0]['HostedZone']['Id'] return delete_hosted_zone(Id=Id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "delete_hosted_zone_by_domain", "(", "Name", ",", "PrivateZone", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "args", "=", "{", "'Name'", ":", "Name", ",", ...
Delete a Route53 hosted zone by domain name, and PrivateZone status if provided. CLI Example:: salt myminion boto3_route53.delete_hosted_zone_by_domain example.org.
[ "Delete", "a", "Route53", "hosted", "zone", "by", "domain", "name", "and", "PrivateZone", "status", "if", "provided", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L703-L721
train
saltstack/salt
salt/modules/boto3_route53.py
aws_encode
def aws_encode(x): ''' An implementation of the encoding required to suport AWS's domain name rules defined here__: .. __: http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html While AWS's documentation specifies individual ASCII characters which need to be encoded, we instead just try to force the string to one of escaped unicode or idna depending on whether there are non-ASCII characters present. This means that we support things like ドメイン.テスト as a domain name string. More information about IDNA encoding in python is found here__: .. __: https://pypi.org/project/idna ''' ret = None try: x.encode('ascii') ret = re.sub(r'\\x([a-f0-8]{2})', _hexReplace, x.encode('unicode_escape')) except UnicodeEncodeError: ret = x.encode('idna') except Exception as e: log.error("Couldn't encode %s using either 'unicode_escape' or 'idna' codecs", x) raise CommandExecutionError(e) log.debug('AWS-encoded result for %s: %s', x, ret) return ret
python
def aws_encode(x): ''' An implementation of the encoding required to suport AWS's domain name rules defined here__: .. __: http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html While AWS's documentation specifies individual ASCII characters which need to be encoded, we instead just try to force the string to one of escaped unicode or idna depending on whether there are non-ASCII characters present. This means that we support things like ドメイン.テスト as a domain name string. More information about IDNA encoding in python is found here__: .. __: https://pypi.org/project/idna ''' ret = None try: x.encode('ascii') ret = re.sub(r'\\x([a-f0-8]{2})', _hexReplace, x.encode('unicode_escape')) except UnicodeEncodeError: ret = x.encode('idna') except Exception as e: log.error("Couldn't encode %s using either 'unicode_escape' or 'idna' codecs", x) raise CommandExecutionError(e) log.debug('AWS-encoded result for %s: %s', x, ret) return ret
[ "def", "aws_encode", "(", "x", ")", ":", "ret", "=", "None", "try", ":", "x", ".", "encode", "(", "'ascii'", ")", "ret", "=", "re", ".", "sub", "(", "r'\\\\x([a-f0-8]{2})'", ",", "_hexReplace", ",", "x", ".", "encode", "(", "'unicode_escape'", ")", "...
An implementation of the encoding required to suport AWS's domain name rules defined here__: .. __: http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html While AWS's documentation specifies individual ASCII characters which need to be encoded, we instead just try to force the string to one of escaped unicode or idna depending on whether there are non-ASCII characters present. This means that we support things like ドメイン.テスト as a domain name string. More information about IDNA encoding in python is found here__: .. __: https://pypi.org/project/idna
[ "An", "implementation", "of", "the", "encoding", "required", "to", "suport", "AWS", "s", "domain", "name", "rules", "defined", "here__", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L724-L754
train
saltstack/salt
salt/modules/boto3_route53.py
_aws_encode_changebatch
def _aws_encode_changebatch(o): ''' helper method to process a change batch & encode the bits which need encoding. ''' change_idx = 0 while change_idx < len(o['Changes']): o['Changes'][change_idx]['ResourceRecordSet']['Name'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['Name']) if 'ResourceRecords' in o['Changes'][change_idx]['ResourceRecordSet']: rr_idx = 0 while rr_idx < len(o['Changes'][change_idx]['ResourceRecordSet']['ResourceRecords']): o['Changes'][change_idx]['ResourceRecordSet']['ResourceRecords'][rr_idx]['Value'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['ResourceRecords'][rr_idx]['Value']) rr_idx += 1 if 'AliasTarget' in o['Changes'][change_idx]['ResourceRecordSet']: o['Changes'][change_idx]['ResourceRecordSet']['AliasTarget']['DNSName'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['AliasTarget']['DNSName']) change_idx += 1 return o
python
def _aws_encode_changebatch(o): ''' helper method to process a change batch & encode the bits which need encoding. ''' change_idx = 0 while change_idx < len(o['Changes']): o['Changes'][change_idx]['ResourceRecordSet']['Name'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['Name']) if 'ResourceRecords' in o['Changes'][change_idx]['ResourceRecordSet']: rr_idx = 0 while rr_idx < len(o['Changes'][change_idx]['ResourceRecordSet']['ResourceRecords']): o['Changes'][change_idx]['ResourceRecordSet']['ResourceRecords'][rr_idx]['Value'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['ResourceRecords'][rr_idx]['Value']) rr_idx += 1 if 'AliasTarget' in o['Changes'][change_idx]['ResourceRecordSet']: o['Changes'][change_idx]['ResourceRecordSet']['AliasTarget']['DNSName'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['AliasTarget']['DNSName']) change_idx += 1 return o
[ "def", "_aws_encode_changebatch", "(", "o", ")", ":", "change_idx", "=", "0", "while", "change_idx", "<", "len", "(", "o", "[", "'Changes'", "]", ")", ":", "o", "[", "'Changes'", "]", "[", "change_idx", "]", "[", "'ResourceRecordSet'", "]", "[", "'Name'"...
helper method to process a change batch & encode the bits which need encoding.
[ "helper", "method", "to", "process", "a", "change", "batch", "&", "encode", "the", "bits", "which", "need", "encoding", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L757-L772
train
saltstack/salt
salt/modules/boto3_route53.py
get_resource_records
def get_resource_records(HostedZoneId=None, Name=None, StartRecordName=None, StartRecordType=None, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Get all resource records from a given zone matching the provided StartRecordName (if given) or all records in the zone (if not), optionally filtered by a specific StartRecordType. This will return any and all RRs matching, regardless of their special AWS flavors (weighted, geolocation, alias, etc.) so your code should be prepared for potentially large numbers of records back from this function - for example, if you've created a complex geolocation mapping with lots of entries all over the world providing the same server name to many different regional clients. If you want EXACTLY ONE record to operate on, you'll need to implement any logic required to pick the specific RR you care about from those returned. Note that if you pass in Name without providing a value for PrivateZone (either True or False), CommandExecutionError can be raised in the case of both public and private zones matching the domain. XXX FIXME DOCU CLI example:: salt myminion boto3_route53.get_records test.example.org example.org A ''' if not _exactly_one((HostedZoneId, Name)): raise SaltInvocationError('Exactly one of either HostedZoneId or Name must ' 'be provided.') if Name: args = {'Name': Name, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} args.update({'PrivateZone': PrivateZone}) if PrivateZone is not None else None zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return [] HostedZoneId = zone[0]['HostedZone']['Id'] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = [] next_rr_name = StartRecordName next_rr_type = StartRecordType next_rr_id = None done = False while True: if done: return ret args = {'HostedZoneId': HostedZoneId} args.update({'StartRecordName': aws_encode(next_rr_name)}) if next_rr_name else None # Grrr, can't specify type unless name is set... We'll do this via filtering later instead args.update({'StartRecordType': next_rr_type}) if next_rr_name and next_rr_type else None args.update({'StartRecordIdentifier': next_rr_id}) if next_rr_id else None try: r = conn.list_resource_record_sets(**args) rrs = r['ResourceRecordSets'] next_rr_name = r.get('NextRecordName') next_rr_type = r.get('NextRecordType') next_rr_id = r.get('NextRecordIdentifier') for rr in rrs: rr['Name'] = _aws_decode(rr['Name']) # now iterate over the ResourceRecords and replace any encoded # value strings with the decoded versions if 'ResourceRecords' in rr: x = 0 while x < len(rr['ResourceRecords']): if 'Value' in rr['ResourceRecords'][x]: rr['ResourceRecords'][x]['Value'] = _aws_decode(rr['ResourceRecords'][x]['Value']) x += 1 # or if we are an AliasTarget then decode the DNSName if 'AliasTarget' in rr: rr['AliasTarget']['DNSName'] = _aws_decode(rr['AliasTarget']['DNSName']) if StartRecordName and rr['Name'] != StartRecordName: done = True break if StartRecordType and rr['Type'] != StartRecordType: if StartRecordName: done = True break else: # We're filtering by type alone, and there might be more later, so... continue ret += [rr] if not next_rr_name: done = True except ClientError as e: # Try forever on a simple thing like this... if e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) continue raise e
python
def get_resource_records(HostedZoneId=None, Name=None, StartRecordName=None, StartRecordType=None, PrivateZone=None, region=None, key=None, keyid=None, profile=None): ''' Get all resource records from a given zone matching the provided StartRecordName (if given) or all records in the zone (if not), optionally filtered by a specific StartRecordType. This will return any and all RRs matching, regardless of their special AWS flavors (weighted, geolocation, alias, etc.) so your code should be prepared for potentially large numbers of records back from this function - for example, if you've created a complex geolocation mapping with lots of entries all over the world providing the same server name to many different regional clients. If you want EXACTLY ONE record to operate on, you'll need to implement any logic required to pick the specific RR you care about from those returned. Note that if you pass in Name without providing a value for PrivateZone (either True or False), CommandExecutionError can be raised in the case of both public and private zones matching the domain. XXX FIXME DOCU CLI example:: salt myminion boto3_route53.get_records test.example.org example.org A ''' if not _exactly_one((HostedZoneId, Name)): raise SaltInvocationError('Exactly one of either HostedZoneId or Name must ' 'be provided.') if Name: args = {'Name': Name, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} args.update({'PrivateZone': PrivateZone}) if PrivateZone is not None else None zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return [] HostedZoneId = zone[0]['HostedZone']['Id'] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = [] next_rr_name = StartRecordName next_rr_type = StartRecordType next_rr_id = None done = False while True: if done: return ret args = {'HostedZoneId': HostedZoneId} args.update({'StartRecordName': aws_encode(next_rr_name)}) if next_rr_name else None # Grrr, can't specify type unless name is set... We'll do this via filtering later instead args.update({'StartRecordType': next_rr_type}) if next_rr_name and next_rr_type else None args.update({'StartRecordIdentifier': next_rr_id}) if next_rr_id else None try: r = conn.list_resource_record_sets(**args) rrs = r['ResourceRecordSets'] next_rr_name = r.get('NextRecordName') next_rr_type = r.get('NextRecordType') next_rr_id = r.get('NextRecordIdentifier') for rr in rrs: rr['Name'] = _aws_decode(rr['Name']) # now iterate over the ResourceRecords and replace any encoded # value strings with the decoded versions if 'ResourceRecords' in rr: x = 0 while x < len(rr['ResourceRecords']): if 'Value' in rr['ResourceRecords'][x]: rr['ResourceRecords'][x]['Value'] = _aws_decode(rr['ResourceRecords'][x]['Value']) x += 1 # or if we are an AliasTarget then decode the DNSName if 'AliasTarget' in rr: rr['AliasTarget']['DNSName'] = _aws_decode(rr['AliasTarget']['DNSName']) if StartRecordName and rr['Name'] != StartRecordName: done = True break if StartRecordType and rr['Type'] != StartRecordType: if StartRecordName: done = True break else: # We're filtering by type alone, and there might be more later, so... continue ret += [rr] if not next_rr_name: done = True except ClientError as e: # Try forever on a simple thing like this... if e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) continue raise e
[ "def", "get_resource_records", "(", "HostedZoneId", "=", "None", ",", "Name", "=", "None", ",", "StartRecordName", "=", "None", ",", "StartRecordType", "=", "None", ",", "PrivateZone", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", ...
Get all resource records from a given zone matching the provided StartRecordName (if given) or all records in the zone (if not), optionally filtered by a specific StartRecordType. This will return any and all RRs matching, regardless of their special AWS flavors (weighted, geolocation, alias, etc.) so your code should be prepared for potentially large numbers of records back from this function - for example, if you've created a complex geolocation mapping with lots of entries all over the world providing the same server name to many different regional clients. If you want EXACTLY ONE record to operate on, you'll need to implement any logic required to pick the specific RR you care about from those returned. Note that if you pass in Name without providing a value for PrivateZone (either True or False), CommandExecutionError can be raised in the case of both public and private zones matching the domain. XXX FIXME DOCU CLI example:: salt myminion boto3_route53.get_records test.example.org example.org A
[ "Get", "all", "resource", "records", "from", "a", "given", "zone", "matching", "the", "provided", "StartRecordName", "(", "if", "given", ")", "or", "all", "records", "in", "the", "zone", "(", "if", "not", ")", "optionally", "filtered", "by", "a", "specific...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L814-L901
train
saltstack/salt
salt/modules/boto3_route53.py
change_resource_record_sets
def change_resource_record_sets(HostedZoneId=None, Name=None, PrivateZone=None, ChangeBatch=None, region=None, key=None, keyid=None, profile=None): ''' See the `AWS Route53 API docs`__ as well as the `Boto3 documentation`__ for all the details... .. __: https://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html .. __: http://boto3.readthedocs.io/en/latest/reference/services/route53.html#Route53.Client.change_resource_record_sets The syntax for a ChangeBatch parameter is as follows, but note that the permutations of allowed parameters and combinations thereof are quite varied, so perusal of the above linked docs is highly recommended for any non-trival configurations. .. code-block:: text { "Comment": "string", "Changes": [ { "Action": "CREATE"|"DELETE"|"UPSERT", "ResourceRecordSet": { "Name": "string", "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"NAPTR"|"PTR"|"SRV"|"SPF"|"AAAA", "SetIdentifier": "string", "Weight": 123, "Region": "us-east-1"|"us-east-2"|"us-west-1"|"us-west-2"|"ca-central-1"|"eu-west-1"|"eu-west-2"|"eu-central-1"|"ap-southeast-1"|"ap-southeast-2"|"ap-northeast-1"|"ap-northeast-2"|"sa-east-1"|"cn-north-1"|"ap-south-1", "GeoLocation": { "ContinentCode": "string", "CountryCode": "string", "SubdivisionCode": "string" }, "Failover": "PRIMARY"|"SECONDARY", "TTL": 123, "ResourceRecords": [ { "Value": "string" }, ], "AliasTarget": { "HostedZoneId": "string", "DNSName": "string", "EvaluateTargetHealth": True|False }, "HealthCheckId": "string", "TrafficPolicyInstanceId": "string" } }, ] } CLI Example: .. code-block:: bash foo='{ "Name": "my-cname.example.org.", "TTL": 600, "Type": "CNAME", "ResourceRecords": [ { "Value": "my-host.example.org" } ] }' foo=`echo $foo` # Remove newlines salt myminion boto3_route53.change_resource_record_sets DomainName=example.org. \ keyid=A1234567890ABCDEF123 key=xblahblahblah \ ChangeBatch="{'Changes': [{'Action': 'UPSERT', 'ResourceRecordSet': $foo}]}" ''' if not _exactly_one((HostedZoneId, Name)): raise SaltInvocationError('Exactly one of either HostZoneId or Name must be provided.') if Name: args = {'Name': Name, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} args.update({'PrivateZone': PrivateZone}) if PrivateZone is not None else None zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return [] HostedZoneId = zone[0]['HostedZone']['Id'] args = {'HostedZoneId': HostedZoneId, 'ChangeBatch': _aws_encode_changebatch(ChangeBatch)} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) tries = 20 # A bit more headroom while tries: try: r = conn.change_resource_record_sets(**args) return _wait_for_sync(r['ChangeInfo']['Id'], conn, 30) # And a little extra time here except ClientError as e: if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to apply requested changes to the hosted zone %s: %s', (Name or HostedZoneId), six.text_type(e)) raise e return False
python
def change_resource_record_sets(HostedZoneId=None, Name=None, PrivateZone=None, ChangeBatch=None, region=None, key=None, keyid=None, profile=None): ''' See the `AWS Route53 API docs`__ as well as the `Boto3 documentation`__ for all the details... .. __: https://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html .. __: http://boto3.readthedocs.io/en/latest/reference/services/route53.html#Route53.Client.change_resource_record_sets The syntax for a ChangeBatch parameter is as follows, but note that the permutations of allowed parameters and combinations thereof are quite varied, so perusal of the above linked docs is highly recommended for any non-trival configurations. .. code-block:: text { "Comment": "string", "Changes": [ { "Action": "CREATE"|"DELETE"|"UPSERT", "ResourceRecordSet": { "Name": "string", "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"NAPTR"|"PTR"|"SRV"|"SPF"|"AAAA", "SetIdentifier": "string", "Weight": 123, "Region": "us-east-1"|"us-east-2"|"us-west-1"|"us-west-2"|"ca-central-1"|"eu-west-1"|"eu-west-2"|"eu-central-1"|"ap-southeast-1"|"ap-southeast-2"|"ap-northeast-1"|"ap-northeast-2"|"sa-east-1"|"cn-north-1"|"ap-south-1", "GeoLocation": { "ContinentCode": "string", "CountryCode": "string", "SubdivisionCode": "string" }, "Failover": "PRIMARY"|"SECONDARY", "TTL": 123, "ResourceRecords": [ { "Value": "string" }, ], "AliasTarget": { "HostedZoneId": "string", "DNSName": "string", "EvaluateTargetHealth": True|False }, "HealthCheckId": "string", "TrafficPolicyInstanceId": "string" } }, ] } CLI Example: .. code-block:: bash foo='{ "Name": "my-cname.example.org.", "TTL": 600, "Type": "CNAME", "ResourceRecords": [ { "Value": "my-host.example.org" } ] }' foo=`echo $foo` # Remove newlines salt myminion boto3_route53.change_resource_record_sets DomainName=example.org. \ keyid=A1234567890ABCDEF123 key=xblahblahblah \ ChangeBatch="{'Changes': [{'Action': 'UPSERT', 'ResourceRecordSet': $foo}]}" ''' if not _exactly_one((HostedZoneId, Name)): raise SaltInvocationError('Exactly one of either HostZoneId or Name must be provided.') if Name: args = {'Name': Name, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile} args.update({'PrivateZone': PrivateZone}) if PrivateZone is not None else None zone = find_hosted_zone(**args) if not zone: log.error("Couldn't resolve domain name %s to a hosted zone ID.", Name) return [] HostedZoneId = zone[0]['HostedZone']['Id'] args = {'HostedZoneId': HostedZoneId, 'ChangeBatch': _aws_encode_changebatch(ChangeBatch)} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) tries = 20 # A bit more headroom while tries: try: r = conn.change_resource_record_sets(**args) return _wait_for_sync(r['ChangeInfo']['Id'], conn, 30) # And a little extra time here except ClientError as e: if tries and e.response.get('Error', {}).get('Code') == 'Throttling': log.debug('Throttled by AWS API.') time.sleep(3) tries -= 1 continue log.error('Failed to apply requested changes to the hosted zone %s: %s', (Name or HostedZoneId), six.text_type(e)) raise e return False
[ "def", "change_resource_record_sets", "(", "HostedZoneId", "=", "None", ",", "Name", "=", "None", ",", "PrivateZone", "=", "None", ",", "ChangeBatch", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "prof...
See the `AWS Route53 API docs`__ as well as the `Boto3 documentation`__ for all the details... .. __: https://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html .. __: http://boto3.readthedocs.io/en/latest/reference/services/route53.html#Route53.Client.change_resource_record_sets The syntax for a ChangeBatch parameter is as follows, but note that the permutations of allowed parameters and combinations thereof are quite varied, so perusal of the above linked docs is highly recommended for any non-trival configurations. .. code-block:: text { "Comment": "string", "Changes": [ { "Action": "CREATE"|"DELETE"|"UPSERT", "ResourceRecordSet": { "Name": "string", "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"NAPTR"|"PTR"|"SRV"|"SPF"|"AAAA", "SetIdentifier": "string", "Weight": 123, "Region": "us-east-1"|"us-east-2"|"us-west-1"|"us-west-2"|"ca-central-1"|"eu-west-1"|"eu-west-2"|"eu-central-1"|"ap-southeast-1"|"ap-southeast-2"|"ap-northeast-1"|"ap-northeast-2"|"sa-east-1"|"cn-north-1"|"ap-south-1", "GeoLocation": { "ContinentCode": "string", "CountryCode": "string", "SubdivisionCode": "string" }, "Failover": "PRIMARY"|"SECONDARY", "TTL": 123, "ResourceRecords": [ { "Value": "string" }, ], "AliasTarget": { "HostedZoneId": "string", "DNSName": "string", "EvaluateTargetHealth": True|False }, "HealthCheckId": "string", "TrafficPolicyInstanceId": "string" } }, ] } CLI Example: .. code-block:: bash foo='{ "Name": "my-cname.example.org.", "TTL": 600, "Type": "CNAME", "ResourceRecords": [ { "Value": "my-host.example.org" } ] }' foo=`echo $foo` # Remove newlines salt myminion boto3_route53.change_resource_record_sets DomainName=example.org. \ keyid=A1234567890ABCDEF123 key=xblahblahblah \ ChangeBatch="{'Changes': [{'Action': 'UPSERT', 'ResourceRecordSet': $foo}]}"
[ "See", "the", "AWS", "Route53", "API", "docs", "__", "as", "well", "as", "the", "Boto3", "documentation", "__", "for", "all", "the", "details", "..." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L904-L1002
train
saltstack/salt
salt/utils/sanitizers.py
mask_args_value
def mask_args_value(data, mask): ''' Mask a line in the data, which matches "mask". This can be used for cases where values in your roster file may contain sensitive data such as IP addresses, passwords, user names, etc. Note that this works only when ``data`` is a single string (i.e. when the data in the roster is formatted as ``key: value`` pairs in YAML syntax). :param data: String data, already rendered. :param mask: Mask that matches a single line :return: ''' if not mask: return data out = [] for line in data.split(os.linesep): if fnmatch.fnmatch(line.strip(), mask) and ':' in line: key, value = line.split(':', 1) out.append('{}: {}'.format(salt.utils.stringutils.to_unicode(key.strip()), '** hidden **')) else: out.append(line) return '\n'.join(out)
python
def mask_args_value(data, mask): ''' Mask a line in the data, which matches "mask". This can be used for cases where values in your roster file may contain sensitive data such as IP addresses, passwords, user names, etc. Note that this works only when ``data`` is a single string (i.e. when the data in the roster is formatted as ``key: value`` pairs in YAML syntax). :param data: String data, already rendered. :param mask: Mask that matches a single line :return: ''' if not mask: return data out = [] for line in data.split(os.linesep): if fnmatch.fnmatch(line.strip(), mask) and ':' in line: key, value = line.split(':', 1) out.append('{}: {}'.format(salt.utils.stringutils.to_unicode(key.strip()), '** hidden **')) else: out.append(line) return '\n'.join(out)
[ "def", "mask_args_value", "(", "data", ",", "mask", ")", ":", "if", "not", "mask", ":", "return", "data", "out", "=", "[", "]", "for", "line", "in", "data", ".", "split", "(", "os", ".", "linesep", ")", ":", "if", "fnmatch", ".", "fnmatch", "(", ...
Mask a line in the data, which matches "mask". This can be used for cases where values in your roster file may contain sensitive data such as IP addresses, passwords, user names, etc. Note that this works only when ``data`` is a single string (i.e. when the data in the roster is formatted as ``key: value`` pairs in YAML syntax). :param data: String data, already rendered. :param mask: Mask that matches a single line :return:
[ "Mask", "a", "line", "in", "the", "data", "which", "matches", "mask", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/sanitizers.py#L69-L95
train
saltstack/salt
salt/utils/sanitizers.py
InputSanitizer.trim
def trim(value): ''' Raise an exception if value is empty. Otherwise strip it down. :param value: :return: ''' value = (value or '').strip() if not value: raise CommandExecutionError("Empty value during sanitation") return six.text_type(value)
python
def trim(value): ''' Raise an exception if value is empty. Otherwise strip it down. :param value: :return: ''' value = (value or '').strip() if not value: raise CommandExecutionError("Empty value during sanitation") return six.text_type(value)
[ "def", "trim", "(", "value", ")", ":", "value", "=", "(", "value", "or", "''", ")", ".", "strip", "(", ")", "if", "not", "value", ":", "raise", "CommandExecutionError", "(", "\"Empty value during sanitation\"", ")", "return", "six", ".", "text_type", "(", ...
Raise an exception if value is empty. Otherwise strip it down. :param value: :return:
[ "Raise", "an", "exception", "if", "value", "is", "empty", ".", "Otherwise", "strip", "it", "down", ".", ":", "param", "value", ":", ":", "return", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/sanitizers.py#L31-L41
train
saltstack/salt
salt/utils/sanitizers.py
InputSanitizer.filename
def filename(value): ''' Remove everything that would affect paths in the filename :param value: :return: ''' return re.sub('[^a-zA-Z0-9.-_ ]', '', os.path.basename(InputSanitizer.trim(value)))
python
def filename(value): ''' Remove everything that would affect paths in the filename :param value: :return: ''' return re.sub('[^a-zA-Z0-9.-_ ]', '', os.path.basename(InputSanitizer.trim(value)))
[ "def", "filename", "(", "value", ")", ":", "return", "re", ".", "sub", "(", "'[^a-zA-Z0-9.-_ ]'", ",", "''", ",", "os", ".", "path", ".", "basename", "(", "InputSanitizer", ".", "trim", "(", "value", ")", ")", ")" ]
Remove everything that would affect paths in the filename :param value: :return:
[ "Remove", "everything", "that", "would", "affect", "paths", "in", "the", "filename" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/sanitizers.py#L44-L51
train