/docs/MyDocs

To get this branch, use:
bzr branch http://darksoft.org/webbzr/docs/MyDocs

« back to all changes in this revision

Viewing changes to Administration/Server/Provisioning/ansible/variables.txt

  • Committer: Suren A. Chilingaryan
  • Date: 2017-04-03 02:45:17 UTC
  • Revision ID: csa@suren.me-20170403024517-dwzj0z0k1cmhxm7u
Restructuring, OpenShift, Ansible, Git

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
Variables
 
2
=========
 
3
 - Variables (are called facts) and defined in
 
4
    + Ansible inventory
 
5
    + 'defaults/main.yml' of the roles
 
6
    + Ansible also collects facts about the system which can be queried with 
 
7
        ansible nodes -m setup -i inventory.erb
 
8
    + Set in the roles, includes, and current play-book
 
9
    + Also playbooks can install additional facts into the '/etc/ansible/facts.d/'
 
10
 
 
11
 - Defining variables
 
12
    a: 5                                                                - In .yml
 
13
    a=5                                                                 - In erb
 
14
    a=[1,2,3]                                                           - list
 
15
    a={a: 1, b: 2]                                                      - hash
 
16
    
 
17
 - Accessing variables
 
18
    "{{ fact_name }}"                                                   - accessing fact value
 
19
     {{ fact_name | filter }}                                           - accessing the filtered fact value
 
20
        hash[0]                                                         - accessing list elements
 
21
        hpst[0:3]                                                       - first two elements (yes, 3 is not included of the list), will properly return a single element for single-element lists.
 
22
        hash["key"] / hash.key                                          - accessing hashes, key could be a variable if needed
 
23
 
 
24
 
 
25
 - Global variables
 
26
    hostvars                                                            - allows access to facts about other hosts {{ hostvars['test.example.com']['ansible_distribution'] }}
 
27
    groups                                                              - names of all node groups defined in inventory 
 
28
                                                                            accessing parameter of first node in a group {{ hostvars[groups['servers'][0]]['ansible_distribution'] }}
 
29
                                                                            getting a list of parameters from all group members {{ groups['servers']|map('extract', hostvars, 'ansible_distribution')|list }}
 
30
    group_names                                                         - list of all the groups the current host is in
 
31
    play_hosts                                                          - list of hostnames that are in scope for the current play
 
32
    delegate_to                                                         - inventory name of current host doing delegated job
 
33
    playbook_dir                                                        - path to current playbook directory
 
34
    inventory_dir / inventory_file                                      - path to current inventory
 
35
    inventory_hostname                                                  - the hostname of the host executing task as specified in the inventry
 
36
    
 
37
 
 
38
 - Environmental variables
 
39
     {{ lookup('env','HOME') }}                                         - on the local (management) node
 
40
     ansible_env.SOME_VARIABLE                                          - on the remote system
 
41
         
 
42
 - Accessing variables from other hosts
 
43
    hostvars[hostname][fact]
 
44
 
 
45
Priorities
 
46
==========
 
47
        role defaults [1]                                               - least priority
 
48
        inventory INI or script group vars [2]
 
49
        inventory group_vars/all
 
50
        playbook group_vars/all
 
51
        inventory group_vars/*
 
52
        playbook group_vars/*
 
53
        inventory INI or script host vars [2]
 
54
        inventory host_vars/*
 
55
        playbook host_vars/*
 
56
        host facts
 
57
        play vars
 
58
        play vars_prompt
 
59
        play vars_files
 
60
        role vars (defined in role/vars/main.yml)
 
61
        block vars (only for tasks in block)
 
62
        task vars (only for the task)
 
63
        role (and include_role) params
 
64
        include params
 
65
        include_vars
 
66
        set_facts / registered vars
 
67
        extra vars (always win precedence)                              - max priority
 
68
 
 
69
 
 
70
Working with variables
 
71
======================
 
72
    string1 ~ string2                                                   - concatenation (all types are converted to strings if need be)
 
73
    var | <filter>                                                      - executes filter
 
74
    var.func()                                                          - executes function
 
75
    var is <test>                                                       - applies test
 
76
 
 
77
Tests
 
78
=====
 
79
 - Standard
 
80
    var                                                                 - if var is true, list/hash is not empty
 
81
    var is defined/undefined                                            - check if the var is already defined
 
82
    var in []                                                           - var is contained in array
 
83
 
 
84
    var == "string"                                                     - simple string comparison
 
85
    not <condition>
 
86
    cond1 or/and cond2
 
87
    
 
88
 - Advanced
 
89
    var is number/sequence/mapping/iterable
 
90
    var is even/odd/divisibleby(num)
 
91
    
 
92
 
 
93
Functions
 
94
=========
 
95
 - Strings
 
96
    string.split('/')                                                   - split strings into the array
 
97
    string.find("all systems go")  != -1                                - find substring in the string, return -1 if not found
 
98
    string.lower/upper()
 
99
 
 
100
 - Lists
 
101
    list.index('element')                                               - index of the element in the list (will fail if not found)
 
102
 
 
103
 - Dicts
 
104
    dict.keys/values()
 
105
 
 
106
Filters                                                                 - more builtin filters from Jinja2 is possible to use
 
107
=======
 
108
 - Filters
 
109
    var | int,list                                                      - checks if variable of the specified type and performs type conversion, use int(base=16) to parse hexdecimal strings
 
110
    var | type_debug                                                    - display actual type of variable (2.3 only)
 
111
    var | default(5)                                                    - set value if variable is undefined
 
112
    var | version_compare('version', '>=')                              - version test
 
113
    var | to_uuid,hash('md5|blowfish),password_hash('sha256|sha512')    - generate uuid, hashes of variable
 
114
    cond | ternary('true', 'false')                                     - operator '?'
 
115
 
 
116
 - Math
 
117
    var | +,-,/,//,%,*,**                                               - // integer division
 
118
    var | log,root,pow(x)                                               - math
 
119
    var | round(precision, 'common/ceil/floor')                         - rounds number to the specified number of digits after point
 
120
 
 
121
 - Strings
 
122
    var | quote                                                         - add quotes for shell usage
 
123
    var | trim                                                          
 
124
    var | truncate(length, killwords, end, leeway)
 
125
    var | repalce(word, replacement)
 
126
    var | regex_replace('^re$', 'replacement')                          - backreferences are \\1 or \\g<name> if grouped with (?P<name>...)
 
127
    var | regex_escape()                                                - escape special characters in the regex
 
128
 
 
129
 - List Filters
 
130
    var | length,last                                                   - number of elements in the list or get last element on the list
 
131
    var | join(",")                                                     - join elements of the list into the string using specified separator
 
132
    var | min,max                                                       - minimum or maximum in the list
 
133
    var | unique                                                        - uniq subset from the list
 
134
    var | reverse, shuffle                                              - list reordering
 
135
    var | sort(attribute)                                               - sorts the list of strings, or of arbitrary elements by the specified attribute
 
136
    var | union,intersect,difference,symmetric_difference(var2)         - combine two lists
 
137
    var | issubset,issuperset(var2)                                     - checks if list is subset/superset of anotehr list
 
138
    var | random                                                        - gets random element of the list
 
139
    var | slice(#)                                                      - slices list into the list of sublist with each sublist containing the specified number of elements
 
140
    var | sum('<iterable>', attribute=<name>, start=#|[])               - sums up the elements or joins arrays (hashes is not possible)
 
141
    var | map(attribute='name') | list                                  - extracts the specified attribute for all members of the list
 
142
    var | map('<filter>', <parameters>) | list                          - applies 'filter' with 'parameters' to each element of the list (filter is anything from here)
 
143
                                                                            for each element 'item' of 'var' list, 'item | filter(parameters)' will be executed and result stored
 
144
        extract, <list|hash>, key                                       - var should contain indeces/keys of the list/hash supplied in parameters and the 'map' will return appropriate values
 
145
 
 
146
 - Hash Filters
 
147
   var | combine(var2, recursive=true)                                  - combine two hashes
 
148
    
 
149
 - System Types
 
150
    path | basename,dirname,realpath                                    - gets filename/directory from the path or dereference the link
 
151
    path | expanduser                                                   - expands ~ to proper home path
 
152
    path | splitext                                                     - splits extension of the filename and returns it as list of 2 elements
 
153
    path | exists,is_abs,is_dir,is_file,is_link,ismount                 - checks if the path exists, is absolute or rellative, and if it is of a specified type (I guess checked locally)
 
154
    path | samefile(var2)                                               - checks if two paths are linked to the same file
 
155
    
 
156
    cidr | ipaddr,ipv4,ipv6                                             - tests if the variable is CIDR (i.e. ip, network, etc.)
 
157
    cidr | ipaddr('public|private')                                     - check if IP is in private or public range
 
158
    cidr | ipaddr('address|network|netmask')                            - extracts address or network from CIDR
 
159
    cidr | ipaddr('net') | ipaddr('size')                               - get number of IP addresses in the specified range
 
160
    cidr | ipaddr('net') | ipaddr('0|1|-1')                             - get first, second, or the last IP address from the range
 
161
 
 
162
 - Format, Export/Import, and Queries
 
163
    var | filesizeformat(binary)                                        - formats number as human readable size (using power of two if binary set to true)
 
164
    var | b64encode,b64decode                                           - encode/decode variable to base64
 
165
    var | to/from_json/yaml, to_nice_json/yaml(indent=2)                - format and import variables, for instance
 
166
                                                                            set_fact: myvar="{{ result.stdout | from_json }}")
 
167
    var | json_query('query')                                           - if var is a variable with complex structure, the query allows to extract a list of elements from it (kind of XMLPath)
 
168
        path.to.items.item[*].name                                      - extracts names of all elements with name 'item*' under the 'path.to.items'
 
169
        path.to.items.list[?key=='value']                               - from the list 'path.to.items.list' return all items which are of type hash and have 'key' equal to 'value'
 
170
        list[?key=='value'].{key1: key1, key2: key2}                    - extract multiple parameters (key1 & key2) from the selected items and return them as hash with keys (key1 & key2)
 
171
                                                                        actually, query should be passed trough the 'var' to avoid YaML parser confusion
 
172
        path[*].more.path.*                                             - list of lists (last asterix iterates dictionary, but returns its values as list)