%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /usr/lib/python2.7/site-packages/salt/pillar/
Upload File :
Create Path :
Current File : //usr/lib/python2.7/site-packages/salt/pillar/pepa.pyc

�
���^c@@s#dZddlmZmZmZdZdZdZdZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlmZdd	lmZddlZddlZyddlZeZWnek
r�eZnXdZed
krddlZej�Z e j!ddd
�e j!dddddd�e j!dddddd�e j!dddd�e j!dddd�e j!dddddd �e j!d!d"dddd#�e j!d$d%dddd&�e j!d'dd(dd)�e j!d*d+dd,�e j!d-d.dd/�e j"�Z#ej$Z%e#j&rNej'Z%ndZ(e#j)s�yddl*Z*e*j+d0�Z(Wq�ek
r�ej,d1�Z(q�Xnej,d1�Z(ej-�Z.e.j/e%�e.j0e(�ej1d2�Zej/e%�ej2e.�nej1e�Ziid3d46d56d6d76ed86Z3d9�Z4d:�Z5eed;�Z6d<�Z7ed
krej8j9e#j:�s�ej;d=e#j:�ej<d>�nej=j>j?e#j:��#Z@e3jAej=jBjCe@��WdQXdZDxWge3d?D]$ZEeFeGeHeEjI����^q�D] ZJeJd@kr1PneDd>7ZDqWiZKdAe3kr^e3dAZKne#jLr�eKjAej=jBjCe#jL��niZMdBe3kr�e3dBZMne#jNr�eMjAej=jBjCe#jN��ne#j7r�ee3d8<ne#jOrfddlZddlPZPe#jQZQe#jRZReQdkr7edC�ZQneRdkrRePjP�ZRnejSdD�ieQdE6eRdF6dGdH6ZTejUe#jVdIeT�ZWeWjXs�eYdJjZeWj[���neWj\�Z]e]dKddLZ^ejSdM�ie^dN6dOdP6Z_ej`e#jVdQe#jadRe_�ZWeWj\�j`dKig�dZbe#jaebkrVeYdS��nebe#jaZKneZceZddTe3d?eDd@kr�e3d?eDd@dTZcndUe3d?eDd@kr�e3d?eDd@dUZdne6e#jaeMe3d?eDd@dVe3d?eDd@dWeced�Zbe3d8r<e7ebe3d?eDd@dV�nz�ej=jBjejfZgdX�ej=jBje_fdY�Zhe#j)s�ybddliZiddljZiddlkZieleijmej=jBjneb�eijojp�eijqjr���Wqek
r�eheb�qXn
eheb�Wdegej=jBje_fXndS(Zu�
Pepa
====

Configuration templating for SaltStack using Hierarchical substitution and Jinja.

Configuring Pepa
================

.. code-block:: yaml

    extension_modules: /srv/salt/ext

    ext_pillar:
      - pepa:
          resource: host                # Name of resource directory and sub-key in pillars
          sequence:                     # Sequence used for hierarchical substitution
            - hostname:                 # Name of key
                name: input             # Alias used for template directory
                base_only: True         # Only use templates from Base environment, i.e. no staging
            - default:
            - environment:
            - location..region:
                name: region
            - location..country:
                name: country
            - location..datacenter:
                name: datacenter
            - roles:
            - osfinger:
                name: os
            - hostname:
                name: override
                base_only: True
          subkey: True                  # Create a sub-key in pillars, named after the resource in this case [host]
          subkey_only: True             # Only create a sub-key, and leave the top level untouched

    pepa_roots:                         # Base directory for each environment
      base: /srv/pepa/base              # Path for base environment
      dev: /srv/pepa/base               # Associate dev with base
      qa: /srv/pepa/qa
      prod: /srv/pepa/prod

    # Use a different delimiter for nested dictionaries, defaults to '..' since some keys may use '.' in the name
    #pepa_delimiter: ..

    # Supply Grains for Pepa, this should **ONLY** be used for testing or validation
    #pepa_grains:
    #  environment: dev

    # Supply Pillar for Pepa, this should **ONLY** be used for testing or validation
    #pepa_pillars:
    #  saltversion: 0.17.4

    # Enable debug for Pepa, and keep Salt on warning
    #log_level: debug

    #log_granular_levels:
    #  salt: warning
    #  salt.loaded.ext.pillar.pepa: debug

Pepa can also be used in Master-less SaltStack setup.

Command line
============

.. code-block:: bash

    usage: pepa.py [-h] [-c CONFIG] [-d] [-g GRAINS] [-p PILLAR] [-n] [-v]
                   hostname

    positional arguments:
      hostname              Hostname

    optional arguments:
      -h, --help            show this help message and exit
      -c CONFIG, --config CONFIG
                            Configuration file
      -d, --debug           Print debug info
      -g GRAINS, --grains GRAINS
                            Input Grains as YAML
      -p PILLAR, --pillar PILLAR
                            Input Pillar as YAML
      -n, --no-color        No color output
      -v, --validate        Validate output

Templates
=========

Templates is configuration for a host or software, that can use information from Grains or Pillars. These can then be used for hierarchically substitution.

**Example File:** host/input/test_example_com.yaml

.. code-block:: yaml

    location..region: emea
    location..country: nl
    location..datacenter: foobar
    environment: dev
    roles:
      - salt.master
    network..gateway: 10.0.0.254
    network..interfaces..eth0..hwaddr: 00:20:26:a1:12:12
    network..interfaces..eth0..dhcp: False
    network..interfaces..eth0..ipv4: 10.0.0.3
    network..interfaces..eth0..netmask: 255.255.255.0
    network..interfaces..eth0..fqdn: {{ hostname }}
    cobbler..profile: fedora-19-x86_64

As you see in this example you can use Jinja directly inside the template.

**Example File:** host/region/amer.yaml

.. code-block:: yaml

    network..dns..servers:
      - 10.0.0.1
      - 10.0.0.2
    time..ntp..servers:
      - ntp1.amer.example.com
      - ntp2.amer.example.com
      - ntp3.amer.example.com
    time..timezone: America/Chihuahua
    yum..mirror: yum.amer.example.com

Each template is named after the value of the key using lowercase and all extended characters are replaced with underscore.

**Example:**

osfinger: Fedora-19

**Would become:**

fedora_19.yaml

Nested dictionaries
===================

In order to create nested dictionaries as output you can use double dot **".."** as a delimiter. You can change this using "pepa_delimiter" we choose double dot since single dot is already used by key names in some modules, and using ":" requires quoting in the YAML.

**Example:**

.. code-block:: yaml

    network..dns..servers:
      - 10.0.0.1
      - 10.0.0.2
    network..dns..options:
      - timeout:2
      - attempts:1
      - ndots:1
    network..dns..search:
      - example.com

**Would become:**

.. code-block:: yaml

    network:
      dns:
        servers:
          - 10.0.0.1
          - 10.0.0.2
        options:
          - timeout:2
          - attempts:1
          - ndots:1
        search:
          - example.com

Operators
=========

Operators can be used to merge/unset a list/hash or set the key as immutable, so it can't be changed.

=========== ================================================
Operator    Description
=========== ================================================
merge()     Merge list or hash
unset()     Unset key
immutable() Set the key as immutable, so it can't be changed
imerge()    Set immutable and merge
iunset()    Set immutable and unset
=========== ================================================

**Example:**

.. code-block:: yaml

    network..dns..search..merge():
      - foobar.com
      - dummy.nl
    owner..immutable(): Operations
    host..printers..unset():

Validation
==========

Since it's very hard to test Jinja as is, the best approach is to run all the permutations of input and validate the output, i.e. Unit Testing.

To facilitate this in Pepa we use YAML, Jinja and Cerberus <https://github.com/nicolaiarocci/cerberus>.

Schema
======

So this is a validation schema for network configuration, as you see it can be customized with Jinja just as Pepa templates.

This was designed to be run as a build job in Jenkins or similar tool. You can provide Grains/Pillar input using either the config file or command line arguments.

**File Example: host/validation/network.yaml**

.. code-block:: jinja

    network..dns..search:
      type: list
      allowed:
        - example.com

    network..dns..options:
      type: list
      allowed: ['timeout:2', 'attempts:1', 'ndots:1']

    network..dns..servers:
      type: list
      schema:
        regex: ^([0-9]{1,3}\.){3}[0-9]{1,3}$

    network..gateway:
      type: string
      regex: ^([0-9]{1,3}\.){3}[0-9]{1,3}$

    {% if network.interfaces is defined %}
    {% for interface in network.interfaces %}

    network..interfaces..{{ interface }}..dhcp:
      type: boolean

    network..interfaces..{{ interface }}..fqdn:
      type: string
      regex: ^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-zA-Z]{2,6}$

    network..interfaces..{{ interface }}..hwaddr:
      type: string
      regex: ^([0-9a-f]{1,2}\:){5}[0-9a-f]{1,2}$

    network..interfaces..{{ interface }}..ipv4:
      type: string
      regex: ^([0-9]{1,3}\.){3}[0-9]{1,3}$

    network..interfaces..{{ interface }}..netmask:
      type: string
      regex: ^([0-9]{1,3}\.){3}[0-9]{1,3}$

    {% endfor %}
    {% endif %}

Links
=====

For more examples and information see <https://github.com/mickep76/pepa>.
i(tabsolute_importtprint_functiontunicode_literalsu/Michael Persson <michael.ake.persson@gmail.com>u"Copyright (c) 2013 Michael PerssonuApache License, Version 2.0u0.6.6N(tsix(tinputu__main__uhostnamethelpuHostnameu-cu--configtdefaultu/etc/salt/masteruConfiguration fileu-du--debugtactionu
store_trueuPrint debug infou-gu--grainsuInput Grains as YAMLu-pu--pillaruInput Pillar as YAMLu-nu
--no-coloruNo color outputu-vu
--validateuValidate outputu-qu--query-apiu#Query Saltstack REST API for Grainsu--urluhttps://salt:8000uURL for SaltStack REST APIu-uu
--usernameuUsername for SaltStack REST APIu-Pu
--passworduPassword for SaltStack REST APIuI[%(log_color)s%(levelname)-8s%(reset)s] %(log_color)s%(message)s%(reset)su[%(levelname)-8s] %(message)supythonConfigu	/srv/saltubaseu
pepa_rootsu..upepa_delimiteru
pepa_validatecC@sts
tStS(u6
    Only return if all the modules are available
    (tHAS_REQUESTStFalsetTrue(((s4/usr/lib/python2.7/site-packages/salt/pillar/pepa.pyt__virtual__]scC@s�i}x�tj|�D]v\}}|}|jtd�}xNt|d�D]=\}}|t|�krv|||<qK|j|i�}qKWqW|S(u#
    Convert key/value to tree
    upepa_delimiteri(Rt	iteritemstsplitt__opts__t	enumeratetlent
setdefault(tdatattreetflatkeytvaluetttkeystitkey((s4/usr/lib/python2.7/site-packages/salt/pillar/pepa.pytkey_value_to_treegs
cC@sxtd}i}d|d<||d<d|krA|d|d<n'dtkr^td|d<n
d|d<|}g|d<i}	x�g|D]}
ttj|
��^q�D]\\}}||kr�tjd|�q�nd}
t|t	�rd|kr|d}
n|}
d}|rJd	|krJ|d	rJt
jj|d||
�}n t
jj||d||
�}g}t||t
�r�||}n-||s�tjd
|�q�n
||g}xC|D];}d}d}t
jj|tjdd|j��d
�}t
jj|�rtjd|�tjjj|��}tj|j��}WdQX|dj|�yTt|�}tj�|d<|j�|d<|j|�}tjjj|�}Wq.tj k
r�}tj!d||�q.tjjj"k
r}tj!d||�q.Xntjd|�q�|dk	r�x�|D]�}|j#tdd�}d}d}t$|�dkr�|j%d�dkr�|dj&td�}|d}n||	kr�tjd|�qA||	kr�tjd|�qA|dks
|dkr	|dkr0tj'd|||�n!tj'd|||�t(|	|<||krptj!d|�q�t||t)||��s�tj!d|�q�t||t	�r�||j*||�q�t||t
�r�||j+||�q�tj!d |�qA|d!ks!|d"krs|d!kr@tj'd#|�ntj'd$|�t(|	|<||kr�||=q�qA|d%kr�tj'd&|||�t(|	|<||||<qA|dk	r�tj!d'||�qAtj'd(|||�||||<qAWq�q�Wq�Wt|�}i}|r2|j�||<n%|rQ|}|j�||<n|}td)rt|j�|d*<n|S(+u!
    Evaluate Pepa templates
    u
pepa_rootsudefaultuhostnameuenvironmentubaseupepa_templatesuCategory is not defined: %sunameu	base_onlyuCategory has no value set: %su\Wu_u.yamluLoading template: %sNugrainsupillaru%Failed to parse JINJA template: %s
%su'Failed to parse YAML in template: %s
%suTemplate doesn't exist: %supepa_delimiteriu()iu,Key %s is immutable, changes are not allowedumerge()uimerge()uMerge key %s: %su"Set immutable and merge key %s: %su!Cant't merge key %s doesn't existu&Can't merge different types for key %su3Unsupported type need to be list or dict for key %suunset()uiunset()uUnset key %suSet immutable and unset key %suimmutable()u'Set immutable and substitute key %s: %su(Unsupported operator %s, skipping key %suSubstitute key %s: %su
pepa_validateu	pepa_keys(,Rt
__grains__tnextRRtlogtwarningtNonet
isinstancetdicttostpathtjointlisttretsubtlowertisfiletinfotsalttutilstfilestfopentjinja2tTemplatetreadtappendRtcopytrendertyamlt	safe_loadtUndefinedErrorterrort	YAMLErrortrsplitRtrfindtrstriptdebugR
ttypetupdatetextend(t	minion_idtpillartresourcetsequencetsubkeytsubkey_onlytrootstinptoutputt	immutabletstcategR*taliasttempldirtentriestentryt
results_jinjatresultstfntfhrttemplateRterrRtskeytrkeytoperatorRtpillar_data((s4/usr/lib/python2.7/site-packages/salt/pillar/pepa.pyt
ext_pillarws�




5
 



.
'





cC@s�yddl}Wntk
r1tjd�dSXtd}tjj|d|d�}i}g}x�tj|d�D]�}tj	d|�t
jjj
|��}tj|j��}	WdQX|}
tj�|
d	<tj�|
d
<t
jjj|	j|
��}|j|�|j|�qxW|j�}|j|d|�s~x6tj|j�D]\}
}tjd|
|�qXWn||d
<||d<dS(u!
    Validate Pepa templates
    iNu3You need module cerberus in order to use validationu
pepa_rootsubaseuvalidateu/*.yamluLoading schema: %sugrainsupillaru	pepa_keysu Validation failed for key %s: %supepa_schema_keysupepa_schemas(tcerberustImportErrorRtcriticalRR"R#R$tglobR*R+R,R-R.R/R0R1RR3t
__pillar__R5R6R4R?R2t	ValidatortvalidateRRterrorsR(RIRCR\RGtvaldirtall_schemastpepa_schemasRSRTRURtschematvaltekeyR8((s4/usr/lib/python2.7/site-packages/salt/pillar/pepa.pyRb�s2




u$Configuration file doesn't exist: %siu
ext_pillarupepaupepa_grainsupepa_pillaru
Username: uAuthenticate REST APIuusernameupasswordupamueauthu/loginu1Failed to authenticate to SaltStack REST API: {0}ureturnutokenuRequest Grains from REST APIuX-Auth-Tokenuapplication/jsonuAcceptu	/minions/theadersu,Failed to get Grains from SaltStack REST APIusubkeyusubkey_onlyuresourceusequencecC@stS(N(R
(txty((s4/usr/lib/python2.7/site-packages/salt/pillar/pepa.pyt<lambda>sscC@s)ttjjj|dddt��dS(Ntindentitdefault_flow_style(tprintR+R,R5t	safe_dumpR	(tresult((s4/usr/lib/python2.7/site-packages/salt/pillar/pepa.pyt
_print_resultus(st__doc__t
__future__RRRt
__author__t
__copyright__t__license__t__version__R_R/tloggingR"R&tsystsalt.extRtsalt.ext.six.movesRtsalt.utils.filesR+tsalt.utils.yamltrequestsR
RR]R	RRt__name__targparsetArgumentParsertparsertadd_argumentt
parse_argstargstWARNINGt	LOG_LEVELR=tDEBUGt	formattertno_colortcolorlogtColoredFormattert	Formattert
StreamHandlertstreamtsetLeveltsetFormattert	getLoggert
addHandlerRRRR[RbR#R)tconfigR^texitR,R-R.tfh_R?R5R6tlocteRtiterR%RtnameRtgrainsR`RBt	query_apitgetpasstusernametpasswordR*tauthtpostturltrequesttoktRuntimeErrortformatttexttjsontresponsettokenRjtgetthostnameRrt	ex_subkeytex_subkey_onlytSafeOrderedDumpertignore_aliasestorig_ignoreRstpygmentstpygments.lexerstpygments.formattersRpt	highlightRqtlexerst	YamlLexert
formatterstTerminalFormatter(((s4/usr/lib/python2.7/site-packages/salt/pillar/pepa.pyt<module>s


			




	
	�	%"<
	"
	"	
			
	
#
 			


Zerion Mini Shell 1.0