This commit is contained in:
JMARyA 2023-12-04 11:02:23 +01:00
commit c5cd492449
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
475 changed files with 27928 additions and 0 deletions

View file

@ -0,0 +1,23 @@
---
obj: application
website: https://www.ansible.com
repo: https://github.com/ansible/ansible
---
# Ansible
#wip #🐇
Ansible is an open-source automation tool that simplifies configuration management, application deployment, and task automation.
## Inventory
-> https://docs.ansible.com/ansible/latest/inventory_guide/index.html
## Command Line Tools
-> https://docs.ansible.com/ansible/latest/command_guide/index.html
## Playbooks
-> https://docs.ansible.com/ansible/latest/playbook_guide/index.html
See [Ansible Filters](filters/Ansible%20Filters.md), [Ansible Lookup Plugins](lookups/Ansible%20Lookup%20Plugins.md), [Ansible Modules](modules/Ansible%20Modules.md), [Ansible Test Plugins](tests/Ansible%20Test%20Plugins.md).
## Ansible Vault
-> https://docs.ansible.com/ansible/latest/vault_guide/index.html

View file

@ -0,0 +1,37 @@
# Ansible Filters
Ansible filters can be applied to variables to transform them.
## Filters
- [ansible.builtin.urlsplit](ansible.builtin.urlsplit.md)
- [ansible.builtin.unique](ansible.builtin.unique.md)
- [ansible.builtin.to_datetime](ansible.builtin.to_datetime.md)
- [ansible.builtin.strftime](ansible.builtin.strftime.md)
- [ansible.builtin.splitext](ansible.builtin.splitext.md)
- [ansible.builtin.split](ansible.builtin.split.md)
- [ansible.builtin.shuffle](ansible.builtin.shuffle.md)
- [ansible.builtin.regex_findall](ansible.builtin.regex_findall.md)
- [ansible.builtin.regex_search](ansible.builtin.regex_search.md)
- [ansible.builtin.regex_replace](ansible.builtin.regex_replace.md)
- [ansible.builtin.permutations](ansible.builtin.permutations.md)
- [ansible.builtin.md5](ansible.builtin.md5.md)
- [ansible.builtin.intersect](ansible.builtin.intersect.md)
- [ansible.builtin.human_to_bytes](ansible.builtin.human_to_bytes.md)
- [ansible.builtin.human_readable](ansible.builtin.human_readable.md)
- [ansible.builtin.hash](ansible.builtin.hash.md)
- [ansible.builtin.difference](ansible.builtin.difference.md)
- [ansible.builtin.combine](ansible.builtin.combine.md)
- [ansible.builtin.comment](ansible.builtin.comment.md)
- [community.general.json_query](community.general.json_query.md)
### Serialization
- [ansible.builtin.b64decode](ansible.builtin.b64decode.md)
- [ansible.builtin.b64encode](ansible.builtin.b64encode.md)
- [ansible.builtin.to_yaml](ansible.builtin.to_yaml.md)
- [ansible.builtin.to_json](ansible.builtin.to_json.md)
- [ansible.builtin.from_yaml](ansible.builtin.from_yaml.md)
- [ansible.builtin.from_json](ansible.builtin.from_json.md)
### Paths
- [ansible.builtin.relpath](ansible.builtin.relpath.md)
- [ansible.builtin.path_join](ansible.builtin.path_join.md)
- [ansible.builtin.dirname](ansible.builtin.dirname.md)
- [ansible.builtin.commonpath](ansible.builtin.commonpath.md)
- [ansible.builtin.basename](ansible.builtin.basename.md)

View file

@ -0,0 +1,11 @@
# ansible.builtin.b64decode
Decode a base64 string
## Examples
```yaml
# b64 decode a string
lola: "{{ 'bG9sYQ==' | b64decode }}"
# b64 decode the content of 'b64stuff' variable
stuff: "{{ b64stuff | b64encode }}"
```

View file

@ -0,0 +1,11 @@
# ansible.builtin.b64encode
Base64 encoding function.
## Examples
```yml
# b64 encode a string
b64lola: "{{ 'lola'| b64encode }}"
# b64 encode the content of 'stuff' variable
b64stuff: "{{ stuff | b64encode }}"
```

View file

@ -0,0 +1,8 @@
# ansible.builtin.basename
Returns the last name component of a path, what is left in the string that is not dirname.
## Examples
```yml
# To get the last name of a file path, like 'foo.txt' out of '/etc/asdf/foo.txt'.
{{ mypath | basename }}
```

View file

@ -0,0 +1,15 @@
# ansible.builtin.combine
Create a dictionary (hash/associative array) as a result of merging existing dictionaries.
## Examples
```yml
# ab => {'a':1, 'b':3, 'c': 4}
ab: {{ {'a':1, 'b':2} | ansible.builtin.combine({'b':3, 'c':4}) }}
many: "{{ dict1 | ansible.builtin.combine(dict2, dict3, dict4) }}"
# defaults => {'a':{'b':3, 'c':4}, 'd': 5}
# customization => {'a':{'c':20}}
# final => {'a':{'b':3, 'c':20}, 'd': 5}
final: "{{ defaults | ansible.builtin.combine(customization, recursive=true) }}"
```

View file

@ -0,0 +1,13 @@
# ansible.builtin.comment
Use programming language conventions to turn the input string into an embeddable comment.
## Examples
```yml
# commented => #
# # Plain style (default)
# #
commented: "{{ 'Plain style (default)' | comment }}"
# not going to show that here ...
verycustom: "{{ "Custom style" | comment('plain', prefix='#######\n#', postfix='#\n#######\n ###\n #') }}"
```

View file

@ -0,0 +1,9 @@
# ansible.builtin.commonpath
Returns the longest common path from the given list of paths.
## Examples
```yml
# To get the longest common path (for example - '/foo/bar') from the given list of paths
# (for example - ['/foo/bar/foobar','/foo/bar'])
{{ listofpaths | commonpath }}
```

View file

@ -0,0 +1,11 @@
# ansible.builtin.difference
Provide a unique list of all the elements of the first list that do not appear in the second one.
## Examples
```yml
# return the elements of list1 not in list2
# list1: [1, 2, 5, 1, 3, 4, 10]
# list2: [1, 2, 3, 4, 5, 11, 99]
{{ list1 | difference(list2) }}
# => [10]
```

View file

@ -0,0 +1,8 @@
# ansible.builtin.dirname
Returns the head component of a path, basically everything that is not the basename.
## Examples
```yml
# To get the dir name of a file path, like '/etc/asdf' out of '/etc/asdf/foo.txt'.
{{ mypath | dirname }}
```

View file

@ -0,0 +1,11 @@
# ansible.builtin.from_json
Converts a JSON string representation into an equivalent structured Ansible variable.
## Examples
```yml
# variable from string variable containing a JSON document
{{ docker_config | from_json }}
# variable from string JSON document
{{ '{"a": true, "b": 54, "c": [1,2,3]}' | from_json }}
```

View file

@ -0,0 +1,11 @@
# ansible.builtin.from_yaml
Converts a YAML string representation into an equivalent structured Ansible variable.
## Examples
```yml
# variable from string variable containing a YAML document
{{ github_workflow | from_yaml }}
# variable from string JSON document
{{ '{"a": true, "b": 54, "c": [1,2,3]}' | from_yaml }}
```

View file

@ -0,0 +1,10 @@
# ansible.builtin.hash
Returns a configurable hash of the input data. Uses SHA-1 by default.
## Examples
```yml
# sha1_hash => "109f4b3c50d7b0df729d299bc6f8e9ef9066971f"
sha1_hash: {{ 'test2' | hash('sha1') }}
# md5 => "5a105e8b9d40e1329780d62ea2265d8a"
md5: {{ 'test2' | hash('md5') }}
```

View file

@ -0,0 +1,14 @@
# ansible.builtin.human_readable
Convert byte or bit figures to more human readable formats.
## Examples
```yml
# size => "1.15 GB"
size: "{{ 1232345345 | human_readable }}"
# size => "1.15 Gb"
size_bits: "{{ 1232345345 | human_readable(true) }}"
# size => "1175.26 MB"
size_MB: "{{ 1232345345 | human_readable(unit='M') }}"
```

View file

@ -0,0 +1,14 @@
# ansible.builtin.human_to_bytes
Convert a human readable byte or bit string into a number bytes.
## Examples
```yml
# size => 1234803098
size: '{{ "1.15 GB" | human_to_bytes }}'
# size => 1234803098
size: '{{ "1.15" | human_to_bytes(default_unit="G") }}'
# this is an error, wants bits, got bytes
ERROR: '{{ "1.15 GB" | human_to_bytes(isbits=true) }}'
```

View file

@ -0,0 +1,11 @@
# ansible.builtin.intersect
Provide a list with the common elements from other lists.
## Examples
```yml
# return only the common elements of list1 and list2
# list1: [1, 2, 5, 3, 4, 10]
# list2: [1, 2, 3, 4, 5, 11, 99]
{{ list1 | intersect(list2) }}
# => [1, 2, 5, 3, 4]
```

View file

@ -0,0 +1,8 @@
# ansible.builtin.md5
Returns an MD5 hash of the input data
## Examples
```yml
# md5hash => "ae2b1fca515949e5d54fb22b8ed95575"
md5hash: "{{ 'testing' | md5 }}"
```

View file

@ -0,0 +1,20 @@
# ansible.builtin.path_join
Returns a path obtained by joining one or more path components.
If a path component is an absolute path, then all previous components are ignored and joining continues from the absolute path. See examples for details.
## Examples
```yml
# If path == 'foo/bar' and file == 'baz.txt', the result is '/etc/foo/bar/subdir/baz.txt'
{{ ('/etc', path, 'subdir', file) | path_join }}
# equivalent to '/etc/subdir/{{filename}}'
wheremyfile: "{{ ['/etc', 'subdir', filename] | path_join }}"
# trustme => '/etc/apt/trusted.d/mykey.gpg'
trustme: "{{ ['/etc', 'apt', 'trusted.d', 'mykey.gpg'] | path_join }}"
# If one of the paths is absolute, then path_join ignores all previous path components
# If backup_dir == '/tmp' and backup_file == '/sample/baz.txt', the result is '/sample/baz.txt'
# backup_path => "/sample/baz.txt"
backup_path: "{{ ('/etc', backup_dir, backup_file) | path_join }}"
```

View file

@ -0,0 +1,8 @@
# ansible.builtin.permutations
Create a list of the permutations of lists from the elements of a list.
## Examples
```yml
# ptrs_of_two => [ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 1, 5 ], [ 2, 1 ], [ 2, 3 ], [ 2, 4 ], [ 2, 5 ], [ 3, 1 ], [ 3, 2 ], [ 3, 4 ], [ 3, 5 ], [ 4, 1 ], [ 4, 2 ], [ 4, 3 ], [ 4, 5 ], [ 5, 1 ], [ 5, 2 ], [ 5, 3 ], [ 5, 4 ] ]
prts_of_two: "{{ [1,2,3,4,5] | permutations(2) }}"
```

View file

@ -0,0 +1,17 @@
# ansible.builtin.regex_findall
Search in a string or extract all the parts of a string matching a regular expression. Returns all lines matching patterns.
## Examples
```yml
# all_pirates => ['CAR', 'tar', 'bar']
all_pirates: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_findall('^.ar$', multiline=True, ignorecase=True) }}"
# Using inline regex flags instead of passing options to filter
# See https://docs.python.org/3/library/re.html for more information
# on inline regex flags
# all_pirates => ['CAR', 'tar', 'bar']
all_pirates: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_findall('(?im)^.ar$') }}"
# get_ips => ['8.8.8.8', '8.8.4.4']
get_ips: "{{ 'Some DNS servers are 8.8.8.8 and 8.8.4.4' | regex_findall('\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b') }}"
```

View file

@ -0,0 +1,20 @@
# ansible.builtin.regex_replace
Replace a substring defined by a regular expression with another defined by another regular expression based on the first match.
## Examples
```yml
# whatami => 'able'
whatami: "{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}"
# commalocal => 'localhost, 80'
commalocal: "{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}"
# piratecomment => '#CAR\n#tar\nfoo\n#bar\n'
piratecomment: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('^(.ar)$', '#\\1', multiline=True, ignorecase=True) }}"
# Using inline regex flags instead of passing options to filter
# See https://docs.python.org/3/library/re.html for more information
# on inline regex flags
# piratecomment => '#CAR\n#tar\nfoo\n#bar\n'
piratecomment: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('(?im)^(.ar)$', '#\\1') }}"
```

View file

@ -0,0 +1,17 @@
# ansible.builtin.regex_search
Search in a string to extract the part that matches the regular expression. Returns matched string or empty string if no match.
## Examples
```yml
# db => 'database42'
db: "{{ 'server1/database42' | regex_search('database[0-9]+') }}"
# Using inline regex flags instead of passing options to filter
# See https://docs.python.org/3/library/re.html for more information
# on inline regex flags
# server => 'sErver1'
db: "{{ 'sErver1/database42' | regex_search('(?i)server([0-9]+)') }}"
# drinkat => 'BAR'
drinkat: "{{ 'foo\nBAR' | regex_search('^bar', multiline=True, ignorecase=True) }}"
```

View file

@ -0,0 +1,9 @@
# ansible.builtin.relpath
Converts the given path to a relative path from the start, or relative to the directory given in start.
## Examples
```yml
# foobar => ../test/me.txt
testing: "{{ '/tmp/test/me.txt' | relpath('/tmp/other/') }}"
otherrelpath: "{{ mypath | relpath(mydir) }}"
```

View file

@ -0,0 +1,8 @@
# ansible.builtin.shuffle
Take the elements of the input list and return in a random order.
## Examples
```yml
randomized_list: "{{ ['a','b','c'] | shuffle}}"
per_host_repeatable: "{{ ['a','b','c'] | shuffle(seed=inventory_hostname) }}"
```

View file

@ -0,0 +1,11 @@
# ansible.builtin.split
Using Pythons text object method `split` we turn strings into lists via a splitting character.
## Examples
```yml
# listjojo => [ "jojo", "is", "a" ]
listjojo: "{{ 'jojo is a' | split }}"
# listjojocomma => [ "jojo is", "a" ]
listjojocomma: "{{ 'jojo is, a' | split(',') }}"
```

View file

@ -0,0 +1,14 @@
# ansible.builtin.splitext
Returns a list of two, with the elements consisting of filename root and extension.
## Examples
```yml
# gobble => [ '/etc/make', 'conf' ]
gobble: "{{ '/etc/make.conf' | splitext }}"
# file_n_ext => [ 'ansible', 'cfg' ]
file_n_ext: "{{ 'ansible.cfg' | splitext }}"
# hoax => ['/etc/hoasdf', '']
hoax: '{{ "/etc//hoasdf/" | splitext }}'
```

View file

@ -0,0 +1,37 @@
# ansible.builtin.strftime
Using Pythons `strftime` function, take a data formating string and a date/time to create a formated date.
## Parameters
| Parameter | Type | Description |
| ---------- | ----------------- | --------------------------------------------------- |
| **Input** | string / required | A formating string following `stftime` conventions. |
| **second** | integer | Datetime in seconds from `epoch` to format, if not supplied `gmttime/localtime` will be used. |
## Examples
```yml
# for a complete set of features go to https://strftime.org/
# Display year-month-day
{{ '%Y-%m-%d' | strftime }}
# => "2021-03-19"
# Display hour:min:sec
{{ '%H:%M:%S' | strftime }}
# => "21:51:04"
# Use ansible_date_time.epoch fact
{{ '%Y-%m-%d %H:%M:%S' | strftime(ansible_date_time.epoch) }}
# => "2021-03-19 21:54:09"
# Use arbitrary epoch value
{{ '%Y-%m-%d' | strftime(0) }} # => 1970-01-01
{{ '%Y-%m-%d' | strftime(1441357287) }} # => 2015-09-04
# complex examples
vars:
date1: '2022-11-15T03:23:13.686956868Z'
date2: '2021-12-15T16:06:24.400087Z'
date_short: '{{ date1|regex_replace("([^.]+)(\.\d{6})(\d*)(.+)", "\1\2\4") }}' #shorten microseconds
iso8601format: '%Y-%m-%dT%H:%M:%S.%fZ'
date_diff_isoed: '{{ (date1|to_datetime(isoformat) - date2|to_datetime(isoformat)).total_seconds() }}'
```

View file

@ -0,0 +1,21 @@
# ansible.builtin.to_datetime
Using the input string attempt to create a matching Python datetime object.
## Parameters
| Parameter | Type | Description |
| ---------- | ----------------- | ------------------------------------------ |
| **Input** | string / required | A string containing date time information. |
| **format** | string | `strformat` formatted string that describes the expected format of the input string. |
## Examples
```yml
# Get total amount of seconds between two dates. Default date format is %Y-%m-%d %H:%M:%S but you can pass your own format
secsdiff: '{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime("%Y-%m-%d"))).total_seconds() }}'
# Get remaining seconds after delta has been calculated. NOTE: This does NOT convert years, days, hours, and so on to seconds. For that, use total_seconds()
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2016-08-14 18:00:00" | to_datetime)).seconds }}
# This expression evaluates to "12" and not "132". Delta is 2 hours, 12 seconds
# get amount of days between two dates. This returns only number of days and discards remaining hours, minutes, and seconds
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).days }}
```

View file

@ -0,0 +1,11 @@
# ansible.builtin.to_json
Converts an Ansible variable into a [JSON](../../../files/JSON.md) string representation.
## Examples
```yml
# dump variable in a template to create a JSON document
{{ docker_config | to_json }}
# same as above but 'prettier' (equivalent to to_nice_json filter)
{{ docker_config | to_json(indent=4, sort_keys=True) }}
```

View file

@ -0,0 +1,17 @@
# ansible.builtin.to_yaml
Converts an Ansible variable into a [YAML](../../../files/YAML.md) string representation.
## Parameters
| Parameter | Type | Description |
| ---------- | -------------- | ------------------------------------------------------------------------- |
| **Input** | any / required | A variable or expression that returns a data structure. |
| **indent** | integer | Number of spaces to indent structures, mainly used for display to humans. |
## Examples
```yml
# dump variable in a template to create a YAML document
{{ github_workflow | to_yaml }}
# same as above but 'prettier' (equivalent to to_nice_yaml filter)
{{ docker_config | to_yaml(indent=4) }}
```

View file

@ -0,0 +1,10 @@
# ansible.builtin.unique
Creates a list of unique elements (a set) from the provided input list.
## Examples
```yml
# return only the unique elements of list1
# list1: [1, 2, 5, 1, 3, 4, 10]
{{ list1 | unique }}
# => [1, 2, 5, 3, 4, 10]
```

View file

@ -0,0 +1,33 @@
# ansible.builtin.urlsplit
get components from URL
## Parameter
| Parameter | Type | Description |
| --------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------- |
| **query** | "fragment"<br>"hostname"<br>"netloc"<br>"password"<br>"path"<br>"port"<br>"query"<br>"scheme"<br>"username" | Specify a single component to return. |
## Examples
```yaml
parts: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit }}'
# =>
# {
# "fragment": "fragment",
# "hostname": "www.acme.com",
# "netloc": "user:password@www.acme.com:9000",
# "password": "password",
# "path": "/dir/index.html",
# "port": 9000,
# "query": "query=term",
# "scheme": "http",
# "username": "user"
# }
hostname: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit("hostname") }}'
# => 'www.acme.com'
query: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit("query") }}'
# => 'query=term'
path: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit("path") }}'
# => '/dir/index.html'
```

View file

@ -0,0 +1,76 @@
# community.general.json_query
This filter lets you query a complex JSON structure and iterate over it using a loop structure.
## Examples
```yml
- name: Define data to work on in the examples below
ansible.builtin.set_fact:
domain_definition:
domain:
cluster:
- name: cluster1
- name: cluster2
server:
- name: server11
cluster: cluster1
port: '8080'
- name: server12
cluster: cluster1
port: '8090'
- name: server21
cluster: cluster2
port: '9080'
- name: server22
cluster: cluster2
port: '9090'
library:
- name: lib1
target: cluster1
- name: lib2
target: cluster2
- name: Display all cluster names
ansible.builtin.debug:
var: item
loop: "{{ domain_definition | community.general.json_query('domain.cluster[*].name') }}"
- name: Display all server names
ansible.builtin.debug:
var: item
loop: "{{ domain_definition | community.general.json_query('domain.server[*].name') }}"
- name: Display all ports from cluster1
ansible.builtin.debug:
var: item
loop: "{{ domain_definition | community.general.json_query(server_name_cluster1_query) }}"
vars:
server_name_cluster1_query: "domain.server[?cluster=='cluster1'].port"
- name: Display all ports from cluster1 as a string
ansible.builtin.debug:
msg: "{{ domain_definition | community.general.json_query('domain.server[?cluster==`cluster1`].port') | join(', ') }}"
- name: Display all ports from cluster1
ansible.builtin.debug:
var: item
loop: "{{ domain_definition | community.general.json_query('domain.server[?cluster==''cluster1''].port') }}"
- name: Display all server ports and names from cluster1
ansible.builtin.debug:
var: item
loop: "{{ domain_definition | community.general.json_query(server_name_cluster1_query) }}"
vars:
server_name_cluster1_query: "domain.server[?cluster=='cluster2'].{name: name, port: port}"
- name: Display all ports from cluster1
ansible.builtin.debug:
msg: "{{ domain_definition | to_json | from_json | community.general.json_query(server_name_query) }}"
vars:
server_name_query: "domain.server[?starts_with(name,'server1')].port"
- name: Display all ports from cluster1
ansible.builtin.debug:
msg: "{{ domain_definition | to_json | from_json | community.general.json_query(server_name_query) }}"
vars:
server_name_query: "domain.server[?contains(name,'server1')].port"
```

View file

@ -0,0 +1,9 @@
# Ansible Lookup Plugins
Ansible lookup plugins allow you to query information with the `lookup()` function.
- [ansible.builtin.url](ansible.builtin.url.md)
- [ansible.builtin.template](ansible.builtin.template.md)
- [ansible.builtin.ini](ansible.builtin.ini.md)
- [ansible.builtin.file](ansible.builtin.file.md)
- [ansible.builtin.env](ansible.builtin.env.md)
- [ansible.builtin.csvfile](ansible.builtin.csvfile.md)

View file

@ -0,0 +1,32 @@
# ansible.builtin.csvfile
The csvfile lookup reads the contents of a file in [CSV](../../../files/CSV.md) (comma-separated value) format. The lookup looks for the row where the first column matches keyname (which can be multiple words) and returns the value in the col column (default 1, which indexed from 0 means the second column in the file).
## Parameter
| Parameter | Type | Description |
| ------------- | ------ | --------------------------------------------------------------------- |
| **col** | string | column to return (0 indexed). |
| **default** | string | what to return if the value is not found in the file. |
| **delimiter** | string | field separator in the file, for a tab you can specify `TAB` or `\t`. |
| **file** | string | name of the CSV/TSV file to open. |
## Examples
```yml
- name: Match 'Li' on the first column, return the second column (0 based index)
ansible.builtin.debug: msg="The atomic number of Lithium is {{ lookup('ansible.builtin.csvfile', 'Li file=elements.csv delimiter=,') }}"
- name: msg="Match 'Li' on the first column, but return the 3rd column (columns start counting after the match)"
ansible.builtin.debug: msg="The atomic mass of Lithium is {{ lookup('ansible.builtin.csvfile', 'Li file=elements.csv delimiter=, col=2') }}"
- name: Define Values From CSV File, this reads file in one go, but you could also use col= to read each in it's own lookup.
ansible.builtin.set_fact:
loop_ip: "{{ csvline[0] }}"
int_ip: "{{ csvline[1] }}"
int_mask: "{{ csvline[2] }}"
int_name: "{{ csvline[3] }}"
local_as: "{{ csvline[4] }}"
neighbor_as: "{{ csvline[5] }}"
neigh_int_ip: "{{ csvline[6] }}"
vars:
csvline: "{{ lookup('ansible.builtin.csvfile', bgp_neighbor_ip, file='bgp_neighbors.csv', delimiter=',') }}"
delegate_to: localhost
```

View file

@ -0,0 +1,26 @@
# ansible.builtin.env
Allows you to query the environment variables available on the controller when you invoked Ansible.
## Examples
```yml
- name: Basic usage
ansible.builtin.debug:
msg: "'{{ lookup('ansible.builtin.env', 'HOME') }}' is the HOME environment variable."
- name: Before 2.13, how to set default value if the variable is not defined.
This cannot distinguish between USR undefined and USR=''.
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.env', 'USR')|default('nobody', True) }} is the user."
- name: Example how to set default value if the variable is not defined, ignores USR=''
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.env', 'USR', default='nobody') }} is the user."
- name: Set default value to Undefined, if the variable is not defined
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.env', 'USR', default=Undefined) }} is the user."
- name: Set default value to undef(), if the variable is not defined
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.env', 'USR', default=undef()) }} is the user."
```

View file

@ -0,0 +1,22 @@
# ansible.builtin.file
This lookup returns the contents from a file on the Ansible controllers file system.
## Parameters
| Parameter | Type | Description |
| ---------- | ----------------- | ---------------------------------------------------------------------------- |
| **Input** | string / required | path(s) of files to read |
| **lstrip** | boolean | whether or not to remove whitespace from the beginning of the looked-up file |
| **rstrip** | boolean | whether or not to remove whitespace from the ending of the looked-up file |
## Examples
```yml
- ansible.builtin.debug:
msg: "the value of foo.txt is {{ lookup('ansible.builtin.file', '/etc/foo.txt') }}"
- name: display multiple file contents
ansible.builtin.debug: var=item
with_file:
- "/path/to/foo.txt"
- "bar.txt" # will be looked in files/ dir relative to play or in role
- "/path/to/biz.txt"
```

View file

@ -0,0 +1,28 @@
# ansible.builtin.ini
The ini lookup reads the contents of a file in INI format `key1=value1`. This plugin retrieves the value on the right side after the equal sign `'='` of a given section `[section]`.
## Parameters
| Parameter | Type | Description |
| ----------- | ----------------- | ------------------------------------------------- |
| **Input** | string / required | The key(s) to look up. |
| **default** | string | Return value if the key is not in the ini file. |
| **file** | string | Name of the file to load. |
| **re** | boolean | Flag to indicate if the key supplied is a regexp. |
| **section** | string | Section where to lookup the key. |
## Examples
```yml
- ansible.builtin.debug: msg="User in integration is {{ lookup('ansible.builtin.ini', 'user', section='integration', file='users.ini') }}"
- ansible.builtin.debug: msg="User in production is {{ lookup('ansible.builtin.ini', 'user', section='production', file='users.ini') }}"
- ansible.builtin.debug: msg="user.name is {{ lookup('ansible.builtin.ini', 'user.name', type='properties', file='user.properties') }}"
- ansible.builtin.debug:
msg: "{{ item }}"
loop: "{{ q('ansible.builtin.ini', '.*', section='section1', file='test.ini', re=True) }}"
- name: Read an ini file with allow_no_value
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.ini', 'user', file='mysql.ini', section='mysqld', allow_no_value=True) }}"
```

View file

@ -0,0 +1,22 @@
# ansible.builtin.template
Returns a list of strings; for each template in the list of templates you pass in, returns a string containing the results of processing that template.
## Parameters
| Parameter | Type | Description |
| ----------------- | ---------- | ---------------------------------------------------------------------------- |
| **template_vars** | dictionary | A dictionary, the keys become additional variables available for templating. |
## Examples
```yml
- name: show templating results
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.template', './some_template.j2') }}"
- name: show templating results with different variable start and end string
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.template', './some_template.j2', variable_start_string='[%', variable_end_string='%]') }}"
- name: show templating results with different comment start and end string
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.template', './some_template.j2', comment_start_string='[#', comment_end_string='#]') }}"
```

View file

@ -0,0 +1,32 @@
# ansible.builtin.url
Returns the content of the URL requested to be used as data in play.
## Parameters
| Parameter | Type | Description |
| ------------------ | ------------------------- | ---------------------------------------------------------------------------------- |
| **headers** | dictionary | HTTP request headers |
| **password** | string | Password to use for HTTP authentication. |
| **split_lines** | boolean (Default: `true`) | Flag to control if content is returned as a list of lines or as a single text blob |
| **username** | string | Username to use for HTTP authentication. |
| **validate_certs** | boolean (Default: `true`) | Flag to control SSL certificate validation |
## Examples
```yml
- name: url lookup splits lines by default
ansible.builtin.debug: msg="{{item}}"
loop: "{{ lookup('ansible.builtin.url', 'https://github.com/gremlin.keys', wantlist=True) }}"
- name: display ip ranges
ansible.builtin.debug: msg="{{ lookup('ansible.builtin.url', 'https://ip-ranges.amazonaws.com/ip-ranges.json', split_lines=False) }}"
- name: url lookup using authentication
ansible.builtin.debug: msg="{{ lookup('ansible.builtin.url', 'https://some.private.site.com/file.txt', username='bob', password='hunter2') }}"
- name: url lookup using basic authentication
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.url', 'https://some.private.site.com/file.txt', username='bob', password='hunter2', force_basic_auth='True') }}"
- name: url lookup using headers
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.url', 'https://some.private.site.com/api/service', headers={'header1':'value1', 'header2':'value2'} ) }}"
```

View file

@ -0,0 +1,78 @@
# community.mongodb.mongodb
The [MongoDB](../../../applications/MongoDB.md) lookup runs the *find()* command on a given *collection* on a given *MongoDB* server.
The result is a list of jsons, so slightly different from what PyMongo returns. In particular, *timestamps* are converted to epoch integers.
## Parameters
| Parameter | Type | Description |
| ------------------ | -------------------- | ----------------------------------------------------------------------------------------- |
| **collection** | string / required | Name of the collection which the query will be made |
| **connect_string** | string | Can be any valid MongoDB connection string, supporting authentication, replica sets, etc. |
| **database** | string / required | Name of the database which the query will be made |
| **filter** | dictionary | Criteria of the output |
| **limit** | integer | How many results should be shown |
| **projection** | dictionary | Fields you want returned |
| **skip** | integer | How many results should be skipped |
| **sort** | list / elements=list | Sorting rules. |
## Examples
```yml
- hosts: localhost
gather_facts: false
vars:
mongodb_parameters:
#mandatory parameters
database: 'local'
collection: "startup_log"
#optional
connection_string: "mongodb://localhost/"
# connection_string: "mongodb://username:password@my.server.com:27017/"
# extra_connection_parameters: { "ssl" : True , "ssl_certfile": /etc/self_signed_certificate.pem" }
#optional query parameters, we accept any parameter from the normal mongodb query.
# filter: { "hostname": "u18" }
projection: { "pid": True , "_id" : False , "hostname" : True }
skip: 0
limit: 1
sort: [ [ "startTime" , "ASCENDING" ] , [ "age", "DESCENDING" ] ]
tasks:
- debug: msg="The PID from MongoDB is {{ lookup('mongodb', mongodb_parameters ).pid }}"
- debug: msg="The HostName from the MongoDB server is {{ lookup('mongodb', mongodb_parameters ).hostname }}"
- debug: msg="Mongo DB is stored at {{ lookup('mongodb', mongodb_parameters_inline )}}"
vars:
mongodb_parameters_inline:
database: 'local'
collection: "startup_log"
connection_string: "mongodb://localhost/"
limit: 1
projection: { "cmdline.storage": True }
# lookup syntax, does the same as below
- debug: msg="The hostname is {{ item.hostname }} and the pid is {{ item.pid }}"
loop: "{{ lookup('mongodb', mongodb_parameters, wantlist=True) }}"
# query syntax, does the same as above
- debug: msg="The hostname is {{ item.hostname }} and the pid is {{ item.pid }}"
loop: "{{ query('mongodb', mongodb_parameters) }}"
- name: "Raw output from the mongodb lookup (a json with pid and hostname )"
debug: msg="{{ lookup('mongodb', mongodb_parameters) }}"
- name: "Yet another mongodb query, now with the parameters on the task itself"
debug: msg="pid={{item.pid}} hostname={{item.hostname}} version={{ item.buildinfo.version }}"
with_mongodb:
- database: 'local'
collection: "startup_log"
connection_string: "mongodb://localhost/"
limit: 1
projection: { "pid": True , "hostname": True , "buildinfo.version": True }
# Please notice this specific query may result more than one result. This is expected
- name: "Shows the whole output from mongodb"
debug: msg="{{ item }}"
with_mongodb:
- database: 'local'
collection: "startup_log"
connection_string: "mongodb://localhost/"
```

View file

@ -0,0 +1,126 @@
# Ansible Modules
#wip #todo
#todo -> explain modules, sort modules by usage cat
## Builtin
- [ansible.builtin.assert](ansible.builtin.assert.md)
- [ansible.builtin.blockinfile](ansible.builtin.blockinfile.md)
- [ansible.builtin.copy](ansible.builtin.copy.md)
- [ansible.builtin.cron](ansible.builtin.cron.md)
- [ansible.builtin.debug](ansible.builtin.debug.md)
- [ansible.builtin.fail](ansible.builtin.fail.md)
- [ansible.builtin.fetch](ansible.builtin.fetch.md)
- [ansible.builtin.package](ansible.builtin.package.md)
- [ansible.builtin.pause](ansible.builtin.pause.md)
- [ansible.builtin.replace](ansible.builtin.replace.md)
- [ansible.builtin.shell](ansible.builtin.shell.md)
- [ansible.builtin.systemd_service](ansible.builtin.systemd_service.md)
- [ansible.builtin.tempfile](ansible.builtin.tempfile.md)
- [ansible.builtin.template](ansible.builtin.template.md)
- [ansible.builtin.uri](ansible.builtin.uri.md)
- [ansible.builtin.user](ansible.builtin.user.md)
- [ansible.builtin.wait_for](ansible.builtin.wait_for.md)
- [ansible.builtin.lineinfile](ansible.builtin.lineinfile.md)
---
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/iptables_module.html#ansible-collections-ansible-builtin-iptables-module
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html#ansible-collections-ansible-builtin-file-module
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/get_url_module.html#ansible-collections-ansible-builtin-get-url-module
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/git_module.html#ansible-collections-ansible-builtin-git-module
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/group_module.html#ansible-collections-ansible-builtin-group-module
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/hostname_module.html#ansible-collections-ansible-builtin-hostname-module
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/stat_module.html#ansible-collections-ansible-builtin-stat-module
---
- https://docs.ansible.com/ansible/latest/collections/ansible/posix/authorized_key_module.html#ansible-collections-ansible-posix-authorized-key-module
- https://docs.ansible.com/ansible/latest/collections/ansible/posix/mount_module.html#ansible-collections-ansible-posix-mount-module
- https://docs.ansible.com/ansible/latest/collections/ansible/posix/patch_module.html#ansible-collections-ansible-posix-patch-module
- https://docs.ansible.com/ansible/latest/collections/ansible/posix/synchronize_module.html#ansible-collections-ansible-posix-synchronize-module
- https://docs.ansible.com/ansible/latest/collections/ansible/posix/sysctl_module.html#ansible-collections-ansible-posix-sysctl-module
---
- https://docs.ansible.com/ansible/latest/collections/community/crypto/luks_device_module.html#ansible-collections-community-crypto-luks-device-module
- https://docs.ansible.com/ansible/latest/collections/community/crypto/get_certificate_module.html#ansible-collections-community-crypto-get-certificate-module
- https://docs.ansible.com/ansible/latest/collections/community/crypto/openssh_cert_module.html#ansible-collections-community-crypto-openssh-cert-module
- https://docs.ansible.com/ansible/latest/collections/community/crypto/openssh_keypair_module.html#ansible-collections-community-crypto-openssh-keypair-module
---
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_compose_module.html#ansible-collections-community-docker-docker-compose-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_volume_info_module.html#ansible-collections-community-docker-docker-volume-info-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_volume_module.html#ansible-collections-community-docker-docker-volume-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_swarm_service_info_module.html#ansible-collections-community-docker-docker-swarm-service-info-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_swarm_service_module.html#ansible-collections-community-docker-docker-swarm-service-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_swarm_info_module.html#ansible-collections-community-docker-docker-swarm-info-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_prune_module.html#ansible-collections-community-docker-docker-prune-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_node_info_module.html#ansible-collections-community-docker-docker-node-info-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_node_module.html#ansible-collections-community-docker-docker-node-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_network_info_module.html#ansible-collections-community-docker-docker-network-info-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_network_module.html#ansible-collections-community-docker-docker-network-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_login_module.html#ansible-collections-community-docker-docker-login-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_image_load_module.html#ansible-collections-community-docker-docker-image-load-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_image_info_module.html#ansible-collections-community-docker-docker-image-info-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_image_module.html#ansible-collections-community-docker-docker-image-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_container_info_module.html#ansible-collections-community-docker-docker-container-info-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_container_exec_module.html#ansible-collections-community-docker-docker-container-exec-module
- https://docs.ansible.com/ansible/latest/collections/community/docker/docker_container_module.html#ansible-collections-community-docker-docker-container-module
---
- https://docs.ansible.com/ansible/latest/collections/community/general/zpool_facts_module.html#ansible-collections-community-general-zpool-facts-module
- https://docs.ansible.com/ansible/latest/collections/community/general/zfs_facts_module.html#ansible-collections-community-general-zfs-facts-module
- https://docs.ansible.com/ansible/latest/collections/community/general/zfs_module.html#ansible-collections-community-general-zfs-module
- https://docs.ansible.com/ansible/latest/collections/community/general/wakeonlan_module.html#ansible-collections-community-general-wakeonlan-module
- https://docs.ansible.com/ansible/latest/collections/community/general/ufw_module.html#ansible-collections-community-general-ufw-module
- https://docs.ansible.com/ansible/latest/collections/community/general/timezone_module.html#ansible-collections-community-general-timezone-module
- https://docs.ansible.com/ansible/latest/collections/community/general/sysrc_module.html#ansible-collections-community-general-sysrc-module
- https://docs.ansible.com/ansible/latest/collections/community/general/ssh_config_module.html#ansible-collections-community-general-ssh-config-module
- https://docs.ansible.com/ansible/latest/collections/community/general/pacman_module.html#ansible-collections-community-general-pacman-module
- https://docs.ansible.com/ansible/latest/collections/community/general/nmcli_module.html#ansible-collections-community-general-nmcli-module
- https://docs.ansible.com/ansible/latest/collections/community/general/mqtt_module.html#ansible-collections-community-general-mqtt-module
- https://docs.ansible.com/ansible/latest/collections/community/general/matrix_module.html#ansible-collections-community-general-matrix-module
- https://docs.ansible.com/ansible/latest/collections/community/general/mail_module.html#ansible-collections-community-general-mail-module
- https://docs.ansible.com/ansible/latest/collections/community/general/kernel_blacklist_module.html#ansible-collections-community-general-kernel-blacklist-module
- https://docs.ansible.com/ansible/latest/collections/community/general/ini_file_module.html#ansible-collections-community-general-ini-file-module
- https://docs.ansible.com/ansible/latest/collections/community/general/htpasswd_module.html#ansible-collections-community-general-htpasswd-module
- https://docs.ansible.com/ansible/latest/collections/community/general/git_config_module.html#ansible-collections-community-general-git-config-module
- https://docs.ansible.com/ansible/latest/collections/community/general/flatpak_module.html#ansible-collections-community-general-flatpak-module
- https://docs.ansible.com/ansible/latest/collections/community/general/filesystem_module.html#ansible-collections-community-general-filesystem-module
- https://docs.ansible.com/ansible/latest/collections/community/general/crypttab_module.html#ansible-collections-community-general-crypttab-module
- https://docs.ansible.com/ansible/latest/collections/community/general/btrfs_subvolume_module.html#ansible-collections-community-general-btrfs-subvolume-module
- https://docs.ansible.com/ansible/latest/collections/community/general/btrfs_info_module.html#ansible-collections-community-general-btrfs-info-module
- https://docs.ansible.com/ansible/latest/collections/community/general/archive_module.html#ansible-collections-community-general-archive-module
- https://docs.ansible.com/ansible/latest/collections/community/general/apk_module.html#ansible-collections-community-general-apk-module
---
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_volume_info_module.html#ansible-collections-containers-podman-podman-volume-info-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_volume_module.html#ansible-collections-containers-podman-podman-volume-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_save_module.html#ansible-collections-containers-podman-podman-save-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_prune_module.html#ansible-collections-containers-podman-podman-prune-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_network_info_module.html#ansible-collections-containers-podman-podman-network-info-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_network_module.html#ansible-collections-containers-podman-podman-network-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_logout_module.html#ansible-collections-containers-podman-podman-logout-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_login_info_module.html#ansible-collections-containers-podman-podman-login-info-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_login_module.html#ansible-collections-containers-podman-podman-login-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_load_module.html#ansible-collections-containers-podman-podman-load-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_import_module.html#ansible-collections-containers-podman-podman-import-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_image_info_module.html#ansible-collections-containers-podman-podman-image-info-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_image_module.html#ansible-collections-containers-podman-podman-image-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_export_module.html#ansible-collections-containers-podman-podman-export-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_containers_module.html#ansible-collections-containers-podman-podman-containers-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_container_info_module.html#ansible-collections-containers-podman-podman-container-info-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_container_module.html#ansible-collections-containers-podman-podman-container-module
- https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_generate_systemd_module.html#ansible-collections-containers-podman-podman-generate-systemd-module
---
- https://docs.ansible.com/ansible/latest/collections/community/libvirt/virt_module.html#ansible-collections-community-libvirt-virt-module
- https://docs.ansible.com/ansible/latest/collections/community/libvirt/virt_net_module.html#ansible-collections-community-libvirt-virt-net-module
- https://docs.ansible.com/ansible/latest/collections/community/libvirt/virt_pool_module.html#ansible-collections-community-libvirt-virt-pool-module

View file

@ -0,0 +1,42 @@
# ansible.builtin.assert
This module asserts that given expressions are true with an optional custom message
## Parameters
| Parameter | Type | Description |
| ----------- | --------------------------------- | ---------------------------------------------------------------------------------------- |
| **fail_msg** | string | The customized message used for a failing assertion |
| **quiet** | boolean | Set this to `true` to avoid verbose output |
| **success_msg** | string | The customized message used for a successful assertion |
| **that** | list / elements=string / required | A list of string expressions of the same form that can be passed to the when statement |
## Examples
```yaml
- ansible.builtin.assert: { that: "ansible_os_family != 'RedHat'" }
- ansible.builtin.assert:
that:
- "'foo' in some_command_result.stdout"
- number_of_the_counting == 3
- name: After version 2.7 both 'msg' and 'fail_msg' can customize failing assertion message
ansible.builtin.assert:
that:
- my_param <= 100
- my_param >= 0
fail_msg: "'my_param' must be between 0 and 100"
success_msg: "'my_param' is between 0 and 100"
- name: Please use 'msg' when ansible version is smaller than 2.7
ansible.builtin.assert:
that:
- my_param <= 100
- my_param >= 0
msg: "'my_param' must be between 0 and 100"
- name: Use quiet to avoid verbose output
ansible.builtin.assert:
that:
- my_param <= 100
- my_param >= 0
quiet: true
```

View file

@ -0,0 +1,81 @@
# ansible.builtin.blockinfile
This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines
## Parameter
| Parameter | Type | Default | Description |
| ---------------- | --------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **attributes** | string | - | The attributes the resulting filesystem object should have. To get supported flags look at the man page for [chattr](../../../applications/cli/chattr.md) on the target system. The = operator is assumed as default, otherwise + or - operators need to be included in the string. |
| **backup** | boolean | false | Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. |
| **block** | string | "" | The text to insert inside the marker lines. If it is missing or an empty string, the block will be removed as if state were specified to absent. |
| **create** | boolean | false | Create a new file if it does not exist. |
| **group** | string | - | Name of the group that should own the filesystem object, as would be fed to chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership. |
| **insertafter** | string | "EOF" | If specified and no begin/ending marker lines are found, the block will be inserted after the last match of specified regular expression. A special value is available; EOF for inserting the block at the end of the file. If specified regular expression has no matches, EOF will be used instead. The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines. This behaviour was added in ansible-core 2.14. |
| **insertbefore** | string | - | If specified and no begin/ending marker lines are found, the block will be inserted before the last match of specified regular expression.  A special value is available; BOF for inserting the block at the beginning of the file.  If specified regular expression has no matches, the block will be inserted at the end of the file.  The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines. This behaviour was added in ansible-core 2.14. |
| **marker** | string | "# {mark} ANSIBLE MANAGED BLOCK" | The marker line template.  {mark} will be replaced with the values in marker_begin (default=”BEGIN”) and marker_end (default=”END”).  Using a custom marker without the {mark} variable may result in the block being repeatedly inserted on subsequent playbook runs.  Multi-line markers are not supported and will result in the block being repeatedly inserted on subsequent playbook runs.  A newline is automatically appended by the module to marker_begin and marker_end. |
| **marker_begin** | string | "BEGIN" | This will be inserted at `{mark}` in the opening ansible block marker. |
| **marker_end** | string | "END" | This will be inserted at `{mark}` in the closing ansible block marker. |
| **mode** | any | - | The permissions the resulting filesystem object should have. For those used to _/usr/bin/chmod_ remember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example, `'644'` or `'1777'`) so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example, `0755`) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx` or `u=rw,g=r,o=r`). If `mode` is not specified and the destination filesystem object **does not** exist, the default `umask` on the system will be used when setting the mode for the newly created filesystem object. If `mode` is not specified and the destination filesystem object **does** exist, the mode of the existing filesystem object will be used. |
| **owner** | string | - | Name of the user that should own the filesystem object, as would be fed to chown.  When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership.  Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion. |
| **path** | path / required | - | The file to modify. |
| **state** | string | "present" | Whether the block should be there or not. **Choices:** (`"absent"`, `"present"`) |
| **validate** | string | - | The validation command to run before copying the updated file into the final destination.  A temporary file path is used to validate, passed in through %s which must be present as in the examples below.  Also, the command is passed securely so [shell](../../../applications/cli/Shell.md) features such as expansion and pipes will not work. |
## Examples
```yaml
# Before Ansible 2.3, option 'dest' or 'name' was used instead of 'path'
- name: Insert/Update "Match User" configuration block in /etc/ssh/sshd_config
ansible.builtin.blockinfile:
path: /etc/ssh/sshd_config
block: |
Match User ansible-agent
PasswordAuthentication no
- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
(it might be better to copy files into /etc/network/interfaces.d/)
ansible.builtin.blockinfile:
path: /etc/network/interfaces
block: |
iface eth0 inet static
address 192.0.2.23
netmask 255.255.255.0
- name: Insert/Update configuration using a local file and validate it
ansible.builtin.blockinfile:
block: "{{ lookup('ansible.builtin.file', './local/sshd_config') }}"
path: /etc/ssh/sshd_config
backup: yes
validate: /usr/sbin/sshd -T -f %s
- name: Insert/Update HTML surrounded by custom markers after <body> line
ansible.builtin.blockinfile:
path: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
insertafter: "<body>"
block: |
<h1>Welcome to {{ ansible_hostname }}</h1>
<p>Last updated on {{ ansible_date_time.iso8601 }}</p>
- name: Remove HTML as well as surrounding markers
ansible.builtin.blockinfile:
path: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
block: ""
- name: Add mappings to /etc/hosts
ansible.builtin.blockinfile:
path: /etc/hosts
block: |
{{ item.ip }} {{ item.name }}
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
loop:
- { name: host1, ip: 10.10.1.10 }
- { name: host2, ip: 10.10.1.11 }
- { name: host3, ip: 10.10.1.12 }
- name: Search with a multiline search flags regex and if found insert after
blockinfile:
path: listener.ora
block: "{{ listener_line | indent(width=8, first=True) }}"
insertafter: '(?m)SID_LIST_LISTENER_DG =\n.*\(SID_LIST ='
marker: " <!-- {mark} ANSIBLE MANAGED BLOCK -->"
```

View file

@ -0,0 +1,100 @@
# ansible.builtin.copy
The `copy` module copies a file from the local or remote machine to a location on the remote machine.
## Parameter
| Parameter | Type | Default | Description |
| ---------------- | --------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **attributes** | string | - | The attributes the resulting filesystem object should have. To get supported flags look at the man page for [chattr](../../../applications/cli/chattr.md) on the target system. The = operator is assumed as default, otherwise + or - operators need to be included in the string. |
| **backup** | boolean | false | Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. |
| **checksum** | string | - | SHA1 checksum of the file being transferred.  Used to validate that the copy of the file was successful.  If this is not provided, ansible will use the local calculated checksum of the src file. |
| **content** | string | - | When used instead of src, sets the contents of a file directly to the specified value.  Works only when dest is a file. Creates the file if it does not exist.  For advanced formatting or if content contains a variable, use the ansible.builtin.template module. |
| **decrypt** | boolean | true | This option controls the autodecryption of source files using vault. |
| **dest** | path / required | - | Remote absolute path where the file should be copied to. If `src` is a directory, this must be a directory too. If `dest` is a non-existent path and if either `dest` ends with “/” or `src` is a directory, `dest` is created. If _dest_ is a relative path, the starting directory is determined by the remote host. If `src` and `dest` are files, the parent directory of `dest` is not created and the task fails if it does not already exist. |
| **follow** | boolean | false | This flag indicates that filesystem links in the destination, if they exist, should be followed. |
| **force** | boolean | true | Influence whether the remote file must always be replaced. If `true`, the remote file will be replaced when contents are different than the source. If `false`, the file will only be transferred if the destination does not exist. |
| **group** | string | - | Name of the group that should own the filesystem object, as would be fed to chown.  When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership. |
| **local_follow** | boolean | true | This flag indicates that filesystem links in the source tree, if they exist, should be followed. |
| **mode** | any | - | The permissions the resulting filesystem object should have. For those used to _/usr/bin/chmod_ remember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example, `'644'` or `'1777'`) so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example, `0755`) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx` or `u=rw,g=r,o=r`). If `mode` is not specified and the destination filesystem object **does not** exist, the default `umask` on the system will be used when setting the mode for the newly created filesystem object. If `mode` is not specified and the destination filesystem object **does** exist, the mode of the existing filesystem object will be used. |
| **owner** | string | - | Name of the user that should own the filesystem object, as would be fed to chown.  When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership.  Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion. |
| **src** | path | - | Local path to a file to copy to the remote server.  This can be absolute or relative.  If path is a directory, it is copied recursively. In this case, if path ends with “/”, only inside contents of that directory are copied to destination. Otherwise, if it does not end with “/”, the directory itself with all contents is copied. This behavior is similar to the rsync command line tool. |
| **validate** | string | - | The validation command to run before copying the updated file into the final destination.  A temporary file path is used to validate, passed in through %s which must be present as in the examples below.  Also, the command is passed securely so shell features such as expansion and pipes will not work. |
## Return Values
| Value | Type | When | Description |
| --------------- | ------- | ------------------------- | --------------------------------------------- |
| **backup_file** | string | changed and if backup=yes | Name of backup file created |
| **checksum** | string | success | SHA1 checksum of the file after running copy. |
| **dest** | string | success | Destination file/path. |
| **gid** | integer | success | Group id of the file, after execution. |
| **group** | string | success | Group of the file, after execution. |
| **md5sum** | string | when supported | MD5 checksum of the file after running copy. |
| **mode** | string | success | Permissions of the target, after execution. |
| **owner** | string | success | Owner of the file, after execution. |
| **size** | integer | success | Size of the target, after execution. |
| **uid** | integer | success | Owner id of the file, after execution. |
## Examples
```yaml
- name: Copy file with owner and permissions
ansible.builtin.copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
- name: Copy file with owner and permission, using symbolic representation
ansible.builtin.copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u=rw,g=r,o=r
- name: Another symbolic mode example, adding some permissions and removing others
ansible.builtin.copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u+rw,g-wx,o-rwx
- name: Copy a new "ntp.conf" file into place, backing up the original if it differs from the copied version
ansible.builtin.copy:
src: /mine/ntp.conf
dest: /etc/ntp.conf
owner: root
group: root
mode: '0644'
backup: yes
- name: Copy a new "sudoers" file into place, after passing validation with visudo
ansible.builtin.copy:
src: /mine/sudoers
dest: /etc/sudoers
validate: /usr/sbin/visudo -csf %s
- name: Copy a "sudoers" file on the remote machine for editing
ansible.builtin.copy:
src: /etc/sudoers
dest: /etc/sudoers.edit
remote_src: yes
validate: /usr/sbin/visudo -csf %s
- name: Copy using inline content
ansible.builtin.copy:
content: '# This file was moved to /etc/other.conf'
dest: /etc/mine.conf
- name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf
ansible.builtin.copy:
src: /etc/foo.conf
dest: /path/to/link # link to /path/to/file
follow: yes
- name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf
ansible.builtin.copy:
src: /etc/foo.conf
dest: /path/to/link # link to /path/to/file
follow: no
```

View file

@ -0,0 +1,75 @@
# ansible.builtin.cron
Use this module to manage crontab entries. This module allows you to create named crontab entries, update, or delete them.
## Parameter
| Parameter | Type | Default | Description |
| ---------------- | ---------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **backup** | boolean | false | If set, create a backup of the crontab before it is modified. The location of the backup is returned in the `backup_file` variable by this module. |
| **cron_file** | path | - | If specified, uses this file instead of an individual users crontab. The assumption is that this file is exclusively managed by the module, do not use if the file contains multiple entries, NEVER use for /etc/crontab.  If this is a relative path, it is interpreted with respect to /etc/cron.d.  Many linux distros expect (and some require) the filename portion to consist solely of upper- and lower-case letters, digits, underscores, and hyphens.  Using this parameter requires you to specify the user as well, unless state is not present.  Either this parameter or name is required |
| **day** | string | "\*" | Day of the month the job should run (`1-31`, `*`, `*/2`, and so on). |
| **disabled** | boolean | false | If the job should be disabled (commented out) in the crontab.  Only has effect if state=present. |
| **hour** | string | "\*" | Hour when the job should run (`0-23`, `*`, `*/2`, and so on). |
| **job** | string | - | The command to execute. |
| **minute** | string | "\*" | Minute when the job should run (`0-59`, `*`, `*/2`, and so on). |
| **month** | string | "\*" | Month of the year the job should run (`1-12`, `*`, `*/2`, and so on). |
| **name** | string / required | - | Description of a crontab entry. |
| **special_time** | "annually"<br>"daily"<br>"hourly"<br>"monthly"<br>"reboot"<br>"weekly"<br>"yearly" | - | Special time specification nickname. |
| **state** | "absent"<br>"present" | "present" | Whether to ensure the job is present or absent. |
| **user** | string | - | The specific user whose crontab should be modified.  When unset, this parameter defaults to the current user. |
| **weekday** | string | "\*" | Day of the week that the job should run (`0-6` for Sunday-Saturday, `*`, and so on). |
## Examples
```yaml
- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null"
ansible.builtin.cron:
name: "check dirs"
minute: "0"
hour: "5,2"
job: "ls -alh > /dev/null"
- name: 'Ensure an old job is no longer present. Removes any job that is prefixed by "#Ansible: an old job" from the crontab'
ansible.builtin.cron:
name: "an old job"
state: absent
- name: Creates an entry like "@reboot /some/job.sh"
ansible.builtin.cron:
name: "a job for reboot"
special_time: reboot
job: "/some/job.sh"
- name: Creates an entry like "PATH=/opt/bin" on top of crontab
ansible.builtin.cron:
name: PATH
env: yes
job: /opt/bin
- name: Creates an entry like "APP_HOME=/srv/app" and insert it after PATH declaration
ansible.builtin.cron:
name: APP_HOME
env: yes
job: /srv/app
insertafter: PATH
- name: Creates a cron file under /etc/cron.d
ansible.builtin.cron:
name: yum autoupdate
weekday: "2"
minute: "0"
hour: "12"
user: root
job: "YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate"
cron_file: ansible_yum-autoupdate
- name: Removes a cron file from under /etc/cron.d
ansible.builtin.cron:
name: "yum autoupdate"
cron_file: ansible_yum-autoupdate
state: absent
- name: Removes "APP_HOME" environment variable from crontab
ansible.builtin.cron:
name: APP_HOME
env: yes
state: absent
```

View file

@ -0,0 +1,37 @@
# ansible.builtin.debug
This module prints statements during execution and can be useful for debugging variables or expressions without necessarily halting the playbook.
## Parameter
| Parameter | Type | Default | Description |
| ------------- | ------- | -------------- | -------------------------------------------------------------------------------------------------------- |
| **msg** | string | "Hello world!" | The customized message that is printed. If omitted, prints a generic message. |
| **var** | string | - | A variable name to debug.  Mutually exclusive with the msg option. |
| **verbosity** | integer | 0 | A number that controls when the debug is run, if you set to 3 it will only run debug when -vvv or above. |
## Examples
```yaml
- name: Print the gateway for each host when defined
ansible.builtin.debug:
msg: System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}
when: ansible_default_ipv4.gateway is defined
- name: Get uptime information
ansible.builtin.shell: /usr/bin/uptime
register: result
- name: Print return information from the previous task
ansible.builtin.debug:
var: result
verbosity: 2
- name: Display all variables/facts known for a host
ansible.builtin.debug:
var: hostvars[inventory_hostname]
verbosity: 4
- name: Prints two lines of messages, but only if there is an environment value set
ansible.builtin.debug:
msg:
- "Provisioning based on YOUR_KEY which is: {{ lookup('ansible.builtin.env', 'YOUR_KEY') }}"
- "These servers were built using the password of '{{ password_used }}'. Please retain this for later use."
```

View file

@ -0,0 +1,15 @@
# ansible.builtin.fail
This module fails the progress with a custom message.
## Parameter
| Parameter | Type | Default | Description |
| --------- | ------ | ------------------------------- | -------------------------------------------------- |
| **msg** | string | "Failed as requested from task" | The customized message used for failing execution. |
## Examples
```yaml
- name: Example using fail and when together
ansible.builtin.fail:
msg: The system may not be provisioned according to the CMDB status.
when: cmdb_status != "to-be-staged"
```

View file

@ -0,0 +1,39 @@
# ansible.builtin.fetch
- Fetch files from remote nodes
- This module works like [ansible.builtin.copy](ansible.builtin.copy.md), but in reverse.
- It is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname.
- Files that already exist at dest will be overwritten if they are different than the src.
## Parameter
| Parameter | Type | Default | Description |
| --------------------- | ----------------- | ------- | ---------------------------------------------------------------------------------------- |
| **dest** | string / required | - | A directory to save the file into. |
| **fail_on_missing** | boolean | true | When set to `true`, the task will fail if the remote file cannot be read for any reason. |
| **src** | string / required | - | The file on the remote system to fetch.  This must be a file, not a directory. |
| **validate_checksum** | boolean | true | Verify that the source and destination checksums match after the files are fetched. |
## Examples
```yaml
- name: Store file into /tmp/fetched/host.example.com/tmp/somefile
ansible.builtin.fetch:
src: /tmp/somefile
dest: /tmp/fetched
- name: Specifying a path directly
ansible.builtin.fetch:
src: /tmp/somefile
dest: /tmp/prefix-{{ inventory_hostname }}
flat: yes
- name: Specifying a destination path
ansible.builtin.fetch:
src: /tmp/uniquefile
dest: /tmp/special/
flat: yes
- name: Storing in a path relative to the playbook
ansible.builtin.fetch:
src: /tmp/uniquefile
dest: special/prefix-{{ inventory_hostname }}
flat: yes
```

View file

@ -0,0 +1,107 @@
# ansible.builtin.lineinfile
This module ensures a particular line is in a file, or replace an existing line using a back-referenced [regular expression](../../Regex.md).
## Parameter
| Parameter | Type | Default | Description |
| ----------------- | ------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **attributes** | string | - | The attributes the resulting filesystem object should have. To get supported flags look at the man page for [chattr](../../../applications/cli/chattr.md) on the target system. The = operator is assumed as default, otherwise + or - operators need to be included in the string. |
| **backup** | boolean | false | Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. |
| **create** | boolean | false | Create a new file if it does not exist. |
| **firstmatch** | boolean | false | Used with `insertafter` or `insertbefore`.  If set, `insertafter` and `insertbefore` will work with the first line that matches the given [regular expression](../../Regex.md). |
| **group** | string | false | Name of the group that should own the filesystem object, as would be fed to _chown_. |
| **insertafter** | string | - | Used with `state=present`.<br><br>If specified, the line will be inserted after the last match of specified [regular expression](../../Regex.md).<br><br>If the first match is required, use(`firstmatch=yes`).<br><br>A special value is available; `EOF` for inserting the line at the end of the file.<br><br>If specified [regular expression](../../Regex.md) has no matches, `EOF` will be used instead.<br><br>If `insertbefore` is set, default value `EOF` will be ignored. |
| **insertbefore** | string | - | Used with `state=present`.<br><br>If specified, the line will be inserted before the last match of specified [regular expression](../../Regex.md).<br><br>If the first match is required, use `firstmatch=yes`.<br><br>A value is available; `BOF` for inserting the line at the beginning of the file.<br><br>If specified [regular expression](../../Regex.md) has no matches, the line will be inserted at the end of the file. |
| **line** | string | - | The line to insert/replace into the file. |
| **mode** | string | - | The permissions the resulting filesystem object should have. |
| **owner** | string | - | Name of the user that should own the filesystem object, as would be fed to _chown_. |
| **path** | path | - | The file to modify. |
| **regexp** | string | - | The [regular expression](../../Regex.md) to look for in every line of the file. |
| **search_string** | string | - | The literal string to look for in every line of the file. This does not have to match the entire line. |
| **state** | string | "present" | Whether the line should be there or not.<br><br>Choices:<br><br>- `absent`<br>- `present` |
| **validate** | string | - | The validation command to run before copying the updated file into the final destination. |
## Examples
```yaml
# NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- name: Ensure SELinux is set to enforcing mode
ansible.builtin.lineinfile:
path: /etc/selinux/config
regexp: '^SELINUX='
line: SELINUX=enforcing
- name: Make sure group wheel is not in the sudoers configuration
ansible.builtin.lineinfile:
path: /etc/sudoers
state: absent
regexp: '^%wheel'
- name: Replace a localhost entry with our own
ansible.builtin.lineinfile:
path: /etc/hosts
regexp: '^127\.0\.0\.1'
line: 127.0.0.1 localhost
owner: root
group: root
mode: '0644'
- name: Replace a localhost entry searching for a literal string to avoid escaping
ansible.builtin.lineinfile:
path: /etc/hosts
search_string: '127.0.0.1'
line: 127.0.0.1 localhost
owner: root
group: root
mode: '0644'
- name: Ensure the default Apache port is 8080
ansible.builtin.lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: '^Listen '
insertafter: '^#Listen '
line: Listen 8080
- name: Ensure php extension matches new pattern
ansible.builtin.lineinfile:
path: /etc/httpd/conf/httpd.conf
search_string: '<FilesMatch ".php[45]?$">'
insertafter: '^\t<Location \/>\n'
line: ' <FilesMatch ".php[34]?$">'
- name: Ensure we have our own comment added to /etc/services
ansible.builtin.lineinfile:
path: /etc/services
regexp: '^# port for http'
insertbefore: '^www.*80/tcp'
line: '# port for http by default'
- name: Add a line to a file if the file does not exist, without passing regexp
ansible.builtin.lineinfile:
path: /tmp/testfile
line: 192.168.1.99 foo.lab.net foo
create: yes
# NOTE: Yaml requires escaping backslashes in double quotes but not in single quotes
- name: Ensure the JBoss memory settings are exactly as needed
ansible.builtin.lineinfile:
path: /opt/jboss-as/bin/standalone.conf
regexp: '^(.*)Xms(\d+)m(.*)$'
line: '\1Xms${xms}m\3'
backrefs: yes
# NOTE: Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- name: Validate the sudoers file before saving
ansible.builtin.lineinfile:
path: /etc/sudoers
state: present
regexp: '^%ADMIN ALL='
line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
validate: /usr/sbin/visudo -cf %s
# See https://docs.python.org/3/library/re.html for further details on syntax
- name: Use backrefs with alternative group syntax to avoid conflicts with variable values
ansible.builtin.lineinfile:
path: /tmp/config
regexp: ^(host=).*
line: \g<1>{{ hostname }}
backrefs: yes
```

View file

@ -0,0 +1,30 @@
# ansible.builtin.package
Generic OS package manager
## Parameter
| Parameter | Type | Default | Description |
| --------- | --------------------- | ------- | ------------------------------------------------ |
| **name** | string / required | - | Package name, or package specifier with version. |
| **state** | "absent"<br>"present" | - | Whether to install, or remove a package. |
| | | | |
## Examples
```yaml
- name: Install ntpdate
ansible.builtin.package:
name: ntpdate
state: present
# This uses a variable as this changes per distribution.
- name: Remove the apache package
ansible.builtin.package:
name: "{{ apache }}"
state: absent
- name: Install the latest version of Apache and MariaDB
ansible.builtin.package:
name:
- httpd
- mariadb-server
state: latest
```

View file

@ -0,0 +1,37 @@
# ansible.builtin.pause
Pauses playbook execution for a set amount of time, or until a prompt is acknowledged. All parameters are optional. The default behavior is to pause with a prompt.
## Parameter
| Parameter | Type | Default | Description |
| ----------- | ------- | ------- | ------------------------------------------------------------ |
| **echo** | boolean | true | Controls whether or not keyboard input is shown when typing. |
| **minutes** | integer | - | A positive number of minutes to pause for. |
| **prompt** | string | - | Optional text to use for the prompt message. |
| **seconds** | integer | - | A positive number of seconds to pause for. |
## Return Values
| Value | Type | When | Description |
| -------------- | ------ | ---------------------- | ----------------------------------- |
| **delta** | string | always | Time paused in seconds |
| **start** | string | always | Time when started pausing |
| **stop** | string | always | Time when ended pausing |
| **user_input** | string | if no waiting time set | User input from interactive console |
## Examples
```yaml
- name: Pause for 5 minutes to build app cache
ansible.builtin.pause:
minutes: 5
- name: Pause until you can verify updates to an application were successful
ansible.builtin.pause:
- name: A helpful reminder of what to look out for post-update
ansible.builtin.pause:
prompt: "Make sure org.foo.FooOverload exception is not present"
- name: Pause to get some sensitive input
ansible.builtin.pause:
prompt: "Enter a secret"
echo: no
```

View file

@ -0,0 +1,88 @@
# ansible.builtin.replace
Replace all instances of a particular string in a file using a back-referenced regular expression.
## Parameter
| Parameter | Type | Default | Description |
| -------------- | ----------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **after** | string | - | If specified, only content after this match will be replaced/removed. |
| **before** | string | - | If specified, only content before this match will be replaced/removed. |
| **path** | path / required | - | The file to modify. |
| **regexp** | string / required | - | The regular expression to look for in the contents of the file. |
| **replace** | string | "" | The string to replace regexp matches.  May contain backreferences that will get expanded with the regexp capture groups if the regexp matches.  If not set, matches are removed entirely. |
| **attributes** | string | - | The attributes the resulting filesystem object should have. To get supported flags look at the man page for [chattr](../../../applications/cli/chattr.md) on the target system. The = operator is assumed as default, otherwise + or - operators need to be included in the string. |
| **backup** | boolean | false | Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. |
| **follow** | boolean | false | This flag indicates that filesystem links in the destination, if they exist, should be followed. |
| **force** | boolean | true | Influence whether the remote file must always be replaced. If `true`, the remote file will be replaced when contents are different than the source. If `false`, the file will only be transferred if the destination does not exist. |
| **group** | string | - | Name of the group that should own the filesystem object, as would be fed to chown.  When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership. |
| **mode** | any | - | The permissions the resulting filesystem object should have. For those used to _/usr/bin/chmod_ remember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example, `'644'` or `'1777'`) so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example, `0755`) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx` or `u=rw,g=r,o=r`). If `mode` is not specified and the destination filesystem object **does not** exist, the default `umask` on the system will be used when setting the mode for the newly created filesystem object. If `mode` is not specified and the destination filesystem object **does** exist, the mode of the existing filesystem object will be used. |
| **owner** | string | - | Name of the user that should own the filesystem object, as would be fed to chown.  When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership.  Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion. |
| **validate** | string | - | The validation command to run before copying the updated file into the final destination.  A temporary file path is used to validate, passed in through %s which must be present as in the examples below.  Also, the command is passed securely so [shell](../../../applications/cli/Shell.md) features such as expansion and pipes will not work. |
## Examples
```yaml
- name: Replace old hostname with new hostname (requires Ansible >= 2.4)
ansible.builtin.replace:
path: /etc/hosts
regexp: '(\s+)old\.host\.name(\s+.*)?$'
replace: '\1new.host.name\2'
- name: Replace after the expression till the end of the file (requires Ansible >= 2.4)
ansible.builtin.replace:
path: /etc/apache2/sites-available/default.conf
after: 'NameVirtualHost [*]'
regexp: '^(.+)$'
replace: '# \1'
- name: Replace before the expression till the begin of the file (requires Ansible >= 2.4)
ansible.builtin.replace:
path: /etc/apache2/sites-available/default.conf
before: '# live site config'
regexp: '^(.+)$'
replace: '# \1'
# Prior to Ansible 2.7.10, using before and after in combination did the opposite of what was intended.
# see https://github.com/ansible/ansible/issues/31354 for details.
- name: Replace between the expressions (requires Ansible >= 2.4)
ansible.builtin.replace:
path: /etc/hosts
after: '<VirtualHost [*]>'
before: '</VirtualHost>'
regexp: '^(.+)$'
replace: '# \1'
- name: Supports common file attributes
ansible.builtin.replace:
path: /home/jdoe/.ssh/known_hosts
regexp: '^old\.host\.name[^\n]*\n'
owner: jdoe
group: jdoe
mode: '0644'
- name: Supports a validate command
ansible.builtin.replace:
path: /etc/apache/ports
regexp: '^(NameVirtualHost|Listen)\s+80\s*$'
replace: '\1 127.0.0.1:8080'
validate: '/usr/sbin/apache2ctl -f %s -t'
- name: Short form task (in ansible 2+) necessitates backslash-escaped sequences
ansible.builtin.replace: path=/etc/hosts regexp='\\b(localhost)(\\d*)\\b' replace='\\1\\2.localdomain\\2 \\1\\2'
- name: Long form task does not
ansible.builtin.replace:
path: /etc/hosts
regexp: '\b(localhost)(\d*)\b'
replace: '\1\2.localdomain\2 \1\2'
- name: Explicitly specifying positional matched groups in replacement
ansible.builtin.replace:
path: /etc/ssh/sshd_config
regexp: '^(ListenAddress[ ]+)[^\n]+$'
replace: '\g<1>0.0.0.0'
- name: Explicitly specifying named matched groups
ansible.builtin.replace:
path: /etc/ssh/sshd_config
regexp: '^(?P<dctv>ListenAddress[ ]+)(?P<host>[^\n]+)$'
replace: '#\g<dctv>\g<host>\n\g<dctv>0.0.0.0'
```

View file

@ -0,0 +1,78 @@
# ansible.builtin.shell
Execute shell commands on targets.
## Parameter
| Parameter | Type | Default | Description |
| --------------------- | ------- | ------- | -------------------------------------------------------------- |
| **chdir** | path | - | Change into this directory before running the command. |
| **cmd** | string | - | The command to run followed by optional arguments. |
| **creates** | path | - | A filename, when it already exists, this step will not be run. |
| **executable** | path | - | Change the shell used to execute the command. |
| **removes** | path | - | A filename, when it does not exist, this step will not be run. |
| **stdin** | string | - | Set the stdin of the command directly to the specified value. |
| **stdin_add_newline** | boolean | true | Whether to append a newline to stdin data. |
## Return Values
| Value | Type | When | Description |
| ---------------- | ---------------------- | ------ | ------------------------------------------ |
| **cmd** | string | always | The command executed by the task. |
| **delta** | string | always | The command execution delta time. |
| **end** | string | always | The command execution end time. |
| **rc** | integer | always | The command return code (0 means success). |
| **start** | string | always | The command execution start time. |
| **stderr** | string | always | The command standard error. |
| **stderr_lines** | list / elements=string | always | The command standard error split in lines. |
| **stdout** | string | always | The command standard output. |
| **stdout_lines** | list / elements=string | always | The command standard output split in lines. |
## Examples
```yaml
- name: Execute the command in remote shell; stdout goes to the specified file on the remote
ansible.builtin.shell: somescript.sh >> somelog.txt
- name: Change the working directory to somedir/ before executing the command
ansible.builtin.shell: somescript.sh >> somelog.txt
args:
chdir: somedir/
# You can also use the 'args' form to provide the options.
- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist
ansible.builtin.shell: somescript.sh >> somelog.txt
args:
chdir: somedir/
creates: somelog.txt
# You can also use the 'cmd' parameter instead of free form format.
- name: This command will change the working directory to somedir/
ansible.builtin.shell:
cmd: ls -l | grep log
chdir: somedir/
- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
ansible.builtin.shell: cat < /tmp/*txt
args:
executable: /bin/bash
- name: Run a command using a templated variable (always use quote filter to avoid injection)
ansible.builtin.shell: cat {{ myfile|quote }}
# You can use shell to run other executables to perform actions inline
- name: Run expect to wait for a successful PXE boot via out-of-band CIMC
ansible.builtin.shell: |
set timeout 300
spawn ssh admin@{{ cimc_host }}
expect "password:"
send "{{ cimc_password }}\n"
expect "\n{{ cimc_name }}"
send "connect host\n"
expect "pxeboot.n12"
send "\n"
exit 0
args:
executable: /usr/bin/expect
delegate_to: localhost
```

View file

@ -0,0 +1,70 @@
# ansible.builtin.systemd_service
Controls [systemd](../../../linux/Systemd.md) units (services, timers, and so on) on remote hosts.
## Parameter
| Parameter | Type | Default | Description |
| ----------------- | --------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **daemon_reload** | boolean | false | Run daemon-reload before doing any other operations, to make sure systemd has read any changes. |
| **enabled** | boolean | - | Whether the unit should start on boot. **At least one of state and enabled are required.** |
| **force** | boolean | - | Whether to override existing symlinks. |
| **masked** | boolean | - | Whether the unit should be masked or not, a masked unit is impossible to start. |
| **name** | string | - | Name of the unit. This parameter takes the name of exactly one unit to work with. When no extension is given, it is implied to a `.service` as systemd. |
| **scope** | "system"<br>"user"<br>"global" | "system" | Run systemctl within a given service manager scope, either as the default system scope `system`, the current users scope `user`, or the scope of all users `global`. For systemd to work with user, the executing user must have its own instance of dbus started and accessible (systemd requirement). |
| **state** | "reloaded"<br>"restarted"<br>"started"<br>"stopped" | - | `started`/`stopped` are idempotent actions that will not run commands unless necessary. `restarted` will always bounce the unit. `reloaded` will always reload. |
## Return Values
| Value | Type | When | Description |
| ---------- | ---------- | ------- | --------------------------------------------------------------------- |
| **status** | dictionary | success | A dictionary with the key=value pairs returned from `systemctl show`. |
## Examples
```yaml
- name: Make sure a service unit is running
ansible.builtin.systemd:
state: started
name: httpd
- name: Stop service cron on debian, if running
ansible.builtin.systemd:
name: cron
state: stopped
- name: Restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
ansible.builtin.systemd:
state: restarted
daemon_reload: true
name: crond
- name: Reload service httpd, in all cases
ansible.builtin.systemd:
name: httpd.service
state: reloaded
- name: Enable service httpd and ensure it is not masked
ansible.builtin.systemd:
name: httpd
enabled: true
masked: no
- name: Enable a timer unit for dnf-automatic
ansible.builtin.systemd:
name: dnf-automatic.timer
state: started
enabled: true
- name: Just force systemd to reread configs (2.4 and above)
ansible.builtin.systemd:
daemon_reload: true
- name: Just force systemd to re-execute itself (2.8 and above)
ansible.builtin.systemd:
daemon_reexec: true
- name: Run a user service when XDG_RUNTIME_DIR is not set on remote login
ansible.builtin.systemd:
name: myservice
state: started
scope: user
environment:
XDG_RUNTIME_DIR: "/run/user/{{ myuid }}"
```

View file

@ -0,0 +1,35 @@
# ansible.builtin.tempfile
The `tempfile` module creates temporary files and directories.
## Parameter
| Parameter | Type | Default | Description |
| ---------- | --------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| **path** | path | - | Location where temporary file or directory should be created.  If path is not specified, the default system temporary directory will be used. |
| **prefix** | string | "ansible." | Prefix of file/directory name created by module. |
| **state** | "directory"<br>"file" | "file" | Whether to create file or directory. |
| **suffix** | string | "" | Suffix of file/directory name created by module. |
## Return Values
| Value | Type | When | Description |
| -------- | ------ | ------- | ---------------------------------- |
| **path** | string | success | Path to created file or directory. |
## Examples
```yaml
- name: Create temporary build directory
ansible.builtin.tempfile:
state: directory
suffix: build
- name: Create temporary file
ansible.builtin.tempfile:
state: file
suffix: temp
register: tempfile_1
- name: Use the registered var and the file module to remove the temporary file
ansible.builtin.file:
path: "{{ tempfile_1.path }}"
state: absent
when: tempfile_1.path is defined
```

View file

@ -0,0 +1,66 @@
# ansible.builtin.template
Template a file out to a target host using Jinja Template Engine.
## Parameter
| Parameter | Type | Default | Description |
| -------------- | --------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **dest** | path / required | - | Location to render the template to on the remote machine. |
| **src** | path / required | - | Path of a Jinja2 formatted template on the Ansible controller.  This can be a relative or an absolute path. |
| **attributes** | string | - | The attributes the resulting filesystem object should have. To get supported flags look at the man page for [chattr](../../../applications/cli/chattr.md) on the target system. The = operator is assumed as default, otherwise + or - operators need to be included in the string. |
| **backup** | boolean | false | Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. |
| **follow** | boolean | false | This flag indicates that filesystem links in the destination, if they exist, should be followed. |
| **force** | boolean | true | Influence whether the remote file must always be replaced. If `true`, the remote file will be replaced when contents are different than the source. If `false`, the file will only be transferred if the destination does not exist. |
| **group** | string | - | Name of the group that should own the filesystem object, as would be fed to chown.  When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership. |
| **mode** | any | - | The permissions the resulting filesystem object should have. For those used to _/usr/bin/chmod_ remember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example, `'644'` or `'1777'`) so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example, `0755`) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx` or `u=rw,g=r,o=r`). If `mode` is not specified and the destination filesystem object **does not** exist, the default `umask` on the system will be used when setting the mode for the newly created filesystem object. If `mode` is not specified and the destination filesystem object **does** exist, the mode of the existing filesystem object will be used. |
| **owner** | string | - | Name of the user that should own the filesystem object, as would be fed to chown.  When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership.  Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion. |
| **validate** | string | - | The validation command to run before copying the updated file into the final destination.  A temporary file path is used to validate, passed in through %s which must be present as in the examples below.  Also, the command is passed securely so shell features such as expansion and pipes will not work. |
## Examples
```yaml
- name: Template a file to /etc/file.conf
ansible.builtin.template:
src: /mytemplates/foo.j2
dest: /etc/file.conf
owner: bin
group: wheel
mode: '0644'
- name: Template a file, using symbolic modes (equivalent to 0644)
ansible.builtin.template:
src: /mytemplates/foo.j2
dest: /etc/file.conf
owner: bin
group: wheel
mode: u=rw,g=r,o=r
- name: Copy a version of named.conf that is dependent on the OS. setype obtained by doing ls -Z /etc/named.conf on original file
ansible.builtin.template:
src: named.conf_{{ ansible_os_family }}.j2
dest: /etc/named.conf
group: named
setype: named_conf_t
mode: 0640
- name: Create a DOS-style text file from a template
ansible.builtin.template:
src: config.ini.j2
dest: /share/windows/config.ini
newline_sequence: '\r\n'
- name: Copy a new sudoers file into place, after passing validation with visudo
ansible.builtin.template:
src: /mine/sudoers
dest: /etc/sudoers
validate: /usr/sbin/visudo -cf %s
- name: Update sshd configuration safely, avoid locking yourself out
ansible.builtin.template:
src: etc/ssh/sshd_config.j2
dest: /etc/ssh/sshd_config
owner: root
group: root
mode: '0600'
validate: /usr/sbin/sshd -t -f %s
backup: yes
```

View file

@ -0,0 +1,171 @@
# ansible.builtin.uri
Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE HTTP authentication mechanisms.
## Parameter
| Parameter | Type | Default | Description |
| ------------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **attributes** | string | - | The attributes the resulting filesystem object should have. To get supported flags look at the man page for [chattr](../../../applications/cli/chattr.md) on the target system. The = operator is assumed as default, otherwise + or - operators need to be included in the string. |
| **body** | any | - | The body of the http request/response to the web service. If `body_format` is set to json it will take an already formatted JSON string or convert a data structure into JSON. |
| **body_format** | "form-urlencoded"<br>"json"<br>"raw"<br>"form-multipart" | "raw" | The serialization format of the body. When set to `json`, `form-multipart`, or `form-urlencoded`, encodes the body argument, if needed, and automatically sets the Content-Type header accordingly. |
| **creates** | path | - | A filename, when it already exists, this step will not be run. |
| **dest** | path | - | A path of where to download the file to (if desired). If dest is a directory, the basename of the file on the remote server will be used. |
| **headers** | dictionary | {} | Add custom HTTP headers to a request in the format of a YAML hash |
| **method** | string | "GET" | The HTTP method of the request or response. |
| **removes** | path | - | A filename, when it does not exist, this step will not be run. |
| **status_code** | list / elements=integer | \[200] | A list of valid, numeric, HTTP status codes that signifies success of the request. |
| **timeout** | integer | 30 | The socket level timeout in seconds |
| **url** | string / required | - | HTTP or HTTPS URL |
| **url_password** | string | - | A password for the module to use for Digest, Basic or WSSE authentication. |
| **url_username** | string | - | A username for the module to use for Digest, Basic or WSSE authentication. |
| **validate_certs** | boolean | true | If `false`, SSL certificates will not be validated. |
## Return Values
| Value | Type | When | Description |
| ------------------ | ---------- | --------------------------------------------------- | ----------------------------------------------------------------- |
| **content** | string | status not in status_code or return_content is true | The response body content. |
| **cookies** | dictionary | success | The cookie values placed in cookie jar. |
| **cookies_string** | string | success | The value for future request Cookie headers. |
| **elapsed** | integer | success | The number of seconds that elapsed while performing the download. |
| **msg** | string | always | The HTTP message from the request. |
| **path** | string | dest is defined | destination file/path |
| **redirected** | boolean | success | Whether the request was redirected. |
| **status** | integer | always | The HTTP status code from the request. |
| **url** | string | always | The actual URL used for the request. |
## Examples
```yaml
- name: Check that you can connect (GET) to a page and it returns a status 200
ansible.builtin.uri:
url: http://www.example.com
- name: Check that a page returns successfully but fail if the word AWESOME is not in the page contents
ansible.builtin.uri:
url: http://www.example.com
return_content: true
register: this
failed_when: this is failed or "'AWESOME' not in this.content"
- name: Create a JIRA issue
ansible.builtin.uri:
url: https://your.jira.example.com/rest/api/2/issue/
user: your_username
password: your_pass
method: POST
body: "{{ lookup('ansible.builtin.file','issue.json') }}"
force_basic_auth: true
status_code: 201
body_format: json
- name: Login to a form based webpage, then use the returned cookie to access the app in later tasks
ansible.builtin.uri:
url: https://your.form.based.auth.example.com/index.php
method: POST
body_format: form-urlencoded
body:
name: your_username
password: your_password
enter: Sign in
status_code: 302
register: login
- name: Login to a form based webpage using a list of tuples
ansible.builtin.uri:
url: https://your.form.based.auth.example.com/index.php
method: POST
body_format: form-urlencoded
body:
- [ name, your_username ]
- [ password, your_password ]
- [ enter, Sign in ]
status_code: 302
register: login
- name: Upload a file via multipart/form-multipart
ansible.builtin.uri:
url: https://httpbin.org/post
method: POST
body_format: form-multipart
body:
file1:
filename: /bin/true
mime_type: application/octet-stream
file2:
content: text based file content
filename: fake.txt
mime_type: text/plain
text_form_field: value
- name: Connect to website using a previously stored cookie
ansible.builtin.uri:
url: https://your.form.based.auth.example.com/dashboard.php
method: GET
return_content: true
headers:
Cookie: "{{ login.cookies_string }}"
- name: Queue build of a project in Jenkins
ansible.builtin.uri:
url: http://{{ jenkins.host }}/job/{{ jenkins.job }}/build?token={{ jenkins.token }}
user: "{{ jenkins.user }}"
password: "{{ jenkins.password }}"
method: GET
force_basic_auth: true
status_code: 201
- name: POST from contents of local file
ansible.builtin.uri:
url: https://httpbin.org/post
method: POST
src: file.json
- name: POST from contents of remote file
ansible.builtin.uri:
url: https://httpbin.org/post
method: POST
src: /path/to/my/file.json
remote_src: true
- name: Create workspaces in Log analytics Azure
ansible.builtin.uri:
url: https://www.mms.microsoft.com/Embedded/Api/ConfigDataSources/LogManagementData/Save
method: POST
body_format: json
status_code: [200, 202]
return_content: true
headers:
Content-Type: application/json
x-ms-client-workspace-path: /subscriptions/{{ sub_id }}/resourcegroups/{{ res_group }}/providers/microsoft.operationalinsights/workspaces/{{ w_spaces }}
x-ms-client-platform: ibiza
x-ms-client-auth-token: "{{ token_az }}"
body:
- name: Pause play until a URL is reachable from this host
ansible.builtin.uri:
url: "http://192.0.2.1/some/test"
follow_redirects: none
method: GET
register: _result
until: _result.status == 200
retries: 720 # 720 * 5 seconds = 1hour (60*60/5)
delay: 5 # Every 5 seconds
- name: Provide SSL/TLS ciphers as a list
uri:
url: https://example.org
ciphers:
- '@SECLEVEL=2'
- ECDH+AESGCM
- ECDH+CHACHA20
- ECDH+AES
- DHE+AES
- '!aNULL'
- '!eNULL'
- '!aDSS'
- '!SHA1'
- '!AESCCM'
- name: Provide SSL/TLS ciphers as an OpenSSL formatted cipher list
uri:
url: https://example.org
ciphers: '@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM'
```

View file

@ -0,0 +1,101 @@
# ansible.builtin.user
Manage user accounts and user attributes.
## Parameter
| Parameter | Type | Default | Description |
| ---------------------- | ----------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **append** | boolean | false | If `true`, add the user to the groups specified in `groups`. <br>If `false`, user will only be added to the groups specified in `groups`, removing them from all other groups. |
| **create_home** | boolean | true | Unless set to `false`, a home directory will be made for the user when the account is created or if the home directory does not exist. |
| **expires** | float | - | An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently supported on GNU/[Linux](../../../linux/Linux.md), [FreeBSD](../../../bsd/FreeBSD.md), and DragonFlyBSD. Since Ansible 2.6 you can remove the expiry time by specifying a negative value. Currently supported on GNU/[Linux](../../../linux/Linux.md) and [FreeBSD](../../../bsd/FreeBSD.md) |
| **force** | boolean | false | This only affects `state=absent`, it forces removal of the user and associated directories on supported platforms. The behavior is the same as `userdel --force`, check the man page for `userdel` on your system for details and support. When used with `generate_ssh_key=yes` this forces an existing key to be overwritten. |
| **generate_ssh_key** | boolean | false | Whether to generate a [SSH](../../../applications/SSH.md) key for the user in question. This will **not** overwrite an existing [SSH](../../../applications/SSH.md) key unless used with `force=yes`. |
| **group** | string | - | Optionally sets the users primary group (takes a group name). |
| **groups** | list / elements=string | - | List of groups user will be added to. By default, the user is removed from all other groups. Configure `append` to modify this. When set to an empty string `''`, the user is removed from all groups except the primary group. |
| **home** | path | - | Optionally set the users home directory. |
| **move_home** | boolean | false | If set to `true` when used with `home:` , attempt to move the users old home directory to the specified directory if it isnt there already and the old home exists. |
| **name** | string / required | - | Name of the user to create, remove or modify. |
| **password** | string | - | If provided, set the users password to the provided encrypted hash ([Linux](../../../linux/Linux.md)) or plain text password ([macOS](../../../macos/macOS.md)). You can generate the encrypted hash with the `mkpasswd` command. |
| **remove** | boolean | false | This only affects `state=absent`, it attempts to remove directories associated with the user. The behavior is the same as `userdel --remove`, check the man page for details and support. |
| **shell** | string | - | Optionally set the users [shell](../../../applications/cli/Shell.md). |
| **ssh_key_bits** | integer | - | Optionally specify number of bits in [SSH](../../../applications/SSH.md) key to create.  The default value depends on ssh-keygen. |
| **ssh_key_comment** | string | "ansible-generated on $HOSTNAME" | Optionally define the comment for the [SSH](../../../applications/SSH.md) key. |
| **ssh_key_file** | path | .ssh/id_rsa | Optionally specify the [SSH](../../../applications/SSH.md) key filename.  If this is a relative filename then it will be relative to the users home directory. |
| **ssh_key_passphrase** | string | - | Set a passphrase for the [SSH](../../../applications/SSH.md) key.  If no passphrase is provided, the [SSH](../../../applications/SSH.md) key will default to having no passphrase. |
| **ssh_key_type** | string | "rsa" | Optionally specify the type of [SSH](../../../applications/SSH.md) key to generate. |
| **state** | "present"<br>"absent" | present | Whether the account should exist or not, taking action if the state is different from what is stated. |
| **system** | boolean | false | When creating an account `state=present`, setting this to `true` makes the user a system account. |
| **uid** | integer | - | Optionally sets the UID of the user. |
| **update_password** | "always"<br>"on_create" | "always" | `always` will update passwords if they differ. <br>`on_create` will only set the password for newly created users. |
## Return Values
| Value | Type | When | Description |
| ------------------- | ------- | ----------------------------------------------------------- | -------------------------------------------------------- |
| **append** | boolean | When state is `present` and the user exists | Whether or not to append the user to groups. |
| **comment** | string | When user exists | Comment section from passwd file, usually the user name. |
| **create_home** | boolean | When user does not exist and not check mode | Whether or not to create the home directory. |
| **force** | boolean | When _state_ is `absent` and user exists | Whether or not a user account was forcibly deleted. |
| **group** | integer | When user exists | Primary user group ID |
| **groups** | string | When _groups_ is not empty and _state_ is `present` | List of groups of which the user is a member. |
| **home** | string | When _state_ is `present` | Path to users home directory. |
| **move_home** | boolean | When _state_ is `present` and user exists | Whether or not to move an existing home directory. |
| **name** | string | always | User account name. |
| **remove** | boolean | When _state_ is `absent` and user exists | Whether or not to remove the user account. |
| **shell** | string | When _state_ is `present` | User login [shell](../../../applications/cli/Shell.md). |
| **ssh_fingerprint** | string | When _generate_ssh_key_ is `True` | Fingerprint of generated [SSH](../../../applications/SSH.md) key. |
| **ssh_key_file** | string | When _generate_ssh_key_ is `True` | Path to generated [SSH](../../../applications/SSH.md) private key file. |
| **ssh_public_key** | string | When _generate_ssh_key_ is `True` | Generated [SSH](../../../applications/SSH.md) public key file. |
| **stderr** | string | When stderr is returned by a command that is run | Standard error from running commands. |
| **stdout** | string | When standard output is returned by the command that is run | Standard output from running commands. |
| **uid** | integer | When _uid_ is passed to the module | User ID of the user account. |
## Examples
```yaml
- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
ansible.builtin.user:
name: johnd
comment: John Doe
uid: 1040
group: admin
- name: Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups
ansible.builtin.user:
name: james
shell: /bin/bash
groups: admins,developers
append: yes
- name: Remove the user 'johnd'
ansible.builtin.user:
name: johnd
state: absent
remove: yes
- name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
ansible.builtin.user:
name: jsmith
generate_ssh_key: yes
ssh_key_bits: 2048
ssh_key_file: .ssh/id_rsa
- name: Added a consultant whose account you want to expire
ansible.builtin.user:
name: james18
shell: /bin/zsh
groups: developers
expires: 1422403387
- name: Starting at Ansible 2.6, modify user, remove expiry time
ansible.builtin.user:
name: james18
expires: -1
- name: Set maximum expiration date for password
ansible.builtin.user:
name: ram19
password_expire_max: 10
- name: Set minimum expiration date for password
ansible.builtin.user:
name: pushkar15
password_expire_min: 5
```

View file

@ -0,0 +1,100 @@
# ansible.builtin.wait_for
Waits for a condition before continuing
## Parameter
| Parameter | Type | Default | Description |
| ------------------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **connect_timeout** | integer | 5 | Maximum number of seconds to wait for a connection to happen before closing and retrying. |
| **delay** | integer | 0 | Number of seconds to wait before starting to poll. |
| **host** | string | "127.0.0.1" | A resolvable hostname or IP address to wait for. |
| **msg** | string | - | This overrides the normal error message from a failure to meet the required conditions. |
| **path** | path | - | Path to a file on the filesystem that must exist before continuing. `path` and `port` are mutually exclusive parameters. |
| **port** | integer | - | Port number to poll. `path` and `port` are mutually exclusive parameters. |
| **search_regex** | string | - | Can be used to match a string in either a file or a socket connection. |
| **sleep** | integer | 1 | Number of seconds to sleep between checks. |
| **timeout** | integer | 300 | Maximum number of seconds to wait for, when used with another condition it will force an error. |
| **state** | string | "started" | Either `present`, `started`, or `stopped`, `absent`, or `drained`. <br>When checking a port `started` will ensure the port is open, `stopped` will check that it is closed, `drained` will check for active connections. <br>When checking for a file or a search string `present` or `started` will ensure that the file or string is present before continuing, `absent` will check that file is absent or removed. <br>**Choices:** (`"absent"`, `"drained"`, `"present"`, `"started"`, `"stopped"`) |
## Return Values
| Value | Type | When | Description |
| ----------- | ------- | ------ | ------------------------------------------------ |
| **elapsed** | integer | always | The number of seconds that elapsed while waiting |
## Examples
```yaml
- name: Sleep for 300 seconds and continue with play
ansible.builtin.wait_for:
timeout: 300
delegate_to: localhost
- name: Wait for port 8000 to become open on the host, don't start checking for 10 seconds
ansible.builtin.wait_for:
port: 8000
delay: 10
- name: Waits for port 8000 of any IP to close active connections, don't start checking for 10 seconds
ansible.builtin.wait_for:
host: 0.0.0.0
port: 8000
delay: 10
state: drained
- name: Wait for port 8000 of any IP to close active connections, ignoring connections for specified hosts
ansible.builtin.wait_for:
host: 0.0.0.0
port: 8000
state: drained
exclude_hosts: 10.2.1.2,10.2.1.3
- name: Wait until the file /tmp/foo is present before continuing
ansible.builtin.wait_for:
path: /tmp/foo
- name: Wait until the string "completed" is in the file /tmp/foo before continuing
ansible.builtin.wait_for:
path: /tmp/foo
search_regex: completed
- name: Wait until regex pattern matches in the file /tmp/foo and print the matched group
ansible.builtin.wait_for:
path: /tmp/foo
search_regex: completed (?P<task>\w+)
register: waitfor
- ansible.builtin.debug:
msg: Completed {{ waitfor['match_groupdict']['task'] }}
- name: Wait until the lock file is removed
ansible.builtin.wait_for:
path: /var/lock/file.lock
state: absent
- name: Wait until the process is finished and pid was destroyed
ansible.builtin.wait_for:
path: /proc/3466/status
state: absent
- name: Output customized message when failed
ansible.builtin.wait_for:
path: /tmp/foo
state: present
msg: Timeout to find file /tmp/foo
# Do not assume the inventory_hostname is resolvable and delay 10 seconds at start
- name: Wait 300 seconds for port 22 to become open and contain "OpenSSH"
ansible.builtin.wait_for:
port: 22
host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
search_regex: OpenSSH
delay: 10
connection: local
# Same as above but you normally have ansible_connection set in inventory, which overrides 'connection'
- name: Wait 300 seconds for port 22 to become open and contain "OpenSSH"
ansible.builtin.wait_for:
port: 22
host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
search_regex: OpenSSH
delay: 10
vars:
ansible_connection: local
```

View file

@ -0,0 +1,7 @@
# Ansible Test Plugins
Ansible Test Plugins let you check a variable on a condition.
- [ansible.builtin.exists](ansible.builtin.exists.md)
- [ansible.builtin.success](ansible.builtin.success.md)
- [ansible.builtin.url](ansible.builtin.url.md)
- [ansible.builtin.search](ansible.builtin.search.md)

View file

@ -0,0 +1,9 @@
# ansible.builtin.exists
Check if the provided path maps to an existing filesystem object on the controller (localhost).
## Examples
```yml
vars:
my_etc_hosts_exists: "{{ '/etc/hosts' is exist }}"
list_of_local_files_to_copy_to_remote: "{{ list_of_all_possible_files | select('exists') }}"
```

View file

@ -0,0 +1,16 @@
# ansible.builtin.search
Compare string against regular expression using Pythons `search` function.
## Parameters
| Parameter | Type | Description |
| -------------- | -------------------------- | --------------------------------------- |
| **ignorecase** | boolean (default: `false`) | Use case insenstive matching. |
| **multiline** | boolean (default: `false`) | Match against multiple lines in string. |
| **pattern** | string / required | Regex to match against. |
## Examples
```yml
url: "https://example.com/users/foo/resources/bar"
foundmatch: url is search("https://example.com/users/.*/resources")
alsomatch: url is search("users/.*/resources")
```

View file

@ -0,0 +1,8 @@
# ansible.builtin.success
Tests if task finished successfully, opposite of `failed`. Input is a registered result from an Ansible task.
## Example
```yml
# test 'status' to know how to respond
{{ taskresults is success }}
```

View file

@ -0,0 +1,19 @@
# ansible.builtin.url
Validates a string to conform to the URL standard.
## Parameters
| Parameter | Type | Description |
| ----------- | ---------------------- | ---------------------------------------------------------------------------------------- |
| **schemes** | list / elements=string | Subset of URI schemas to validate against, otherwise **any** scheme is considered valid. |
## Examples
```yml
# simple URL
{{ 'http://example.com' is url }}
# looking only for file transfers URIs
{{ 'mailto://nowone@example.com' is not uri(schemes=['ftp', 'ftps', 'sftp', 'file']) }}
# but it is according to standard
{{ 'mailto://nowone@example.com' is not uri }}
# more complex URL
{{ 'ftp://admin:secret@example.com/path/to/myfile.yml' is url }}
```

View file

@ -0,0 +1,9 @@
---
aliases: ["Torrent"]
website: https://www.bittorrent.org/
obj: concept
---
# BitTorrent
[BitTorrent](https://www.bittorrent.org/) is a communication protocol for peer-to-peer file sharing (P2P), which enables users to distribute data and electronic files over the Internet in a decentralized manner.
Users on the BitTorrent Network are not anonymous, because everyones IP address is known. To torrent anonymously one can use the [I2P](I2P.md) Network with i2psnark.

View file

@ -0,0 +1,383 @@
---
obj: application
source: https://docs.docker.com/compose
repo: https://github.com/docker/compose
---
# Docker Compose
Compose is a tool for defining and running multi-container [Docker](Docker.md) applications. With Compose, you use a [YAML](../files/YAML.md) file to configure your application's services. Then, with a single command, you create and start all the services from your configuration.
## Docker Compose file
The Compose file is a [YAML](../files/YAML.md) file defining:
- Version (Optional)
- Services (Required)
- Networks
- Volumes
- Secrets
## Service Configuration
### `build`
Build specifies the image that should be build for the service instead of using an image directly.
`build` can be specified either as a string containing a path to the build context:
```yaml
version: "3.8"
services:
webapp:
build: ./dir
``````
Or, as an object with the path specified under context and optionally Dockerfile and args:
```yaml
version: "3.8"
services:
webapp:
build:
context: ./dir
dockerfile: Dockerfile-alternate
args:
buildno: 1
```
### `command`
Override the default command.
```yaml
command: bundle exec thin -p 3000
```
The command can also be a list, in a manner similar to dockerfile:
```yaml
command: ["bundle", "exec", "thin", "-p", "3000"]
```
### `depends_on`
`depends_on` expresses startup and shutdown dependencies between services.
```yaml
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
```
### `devices`
`devices` defines a list of device mappings for created containers in the form of `HOST_PATH:CONTAINER_PATH\[:CGROUP_PERMISSIONS]`.
```yaml
devices:
- "/dev/ttyUSB0:/dev/ttyUSB0"
- "/dev/sda:/dev/xvda:rwm"
```
### `entrypoint`
`entrypoint` declares the default entrypoint for the service container. This overrides the ENTRYPOINT instruction from the service's Dockerfile.
If entrypoint is non-null, Compose ignores any default command from the image, for example the CMD instruction in the Dockerfile.
In its short form, the value can be defined as a string:
```yaml
entrypoint: /code/entrypoint.sh
```
### `env_file`
`env_file` adds [environment variables](../linux/Environment%20Variables.md) to the container based on the file content.
```yaml
env_file: .env
```
`env_file` can also be a list. The files in the list are processed from the top down. For the same variable specified in two env files, the value from the last file in the list stands.
```yaml
env_file:
- ./a.env
- ./b.env
```
### `environment`
`environment` defines [environment variables](../linux/Environment%20Variables.md) set in the container. environment can use either an array or a map. Any boolean values; true, false, yes, no, should be enclosed in quotes to ensure they are not converted to True or False by the [YAML](../files/YAML.md) parser.
[Environment variables](../linux/Environment%20Variables.md) can be declared by a single key (no value to equals sign). In this case Compose relies on you to resolve the value. If the value is not resolved, the variable is unset and is removed from the service container environment.
Map syntax:
```yaml
environment:
RACK_ENV: development
SHOW: "true"
USER_INPUT:
```
Array syntax:
```yaml
environment:
- RACK_ENV=development
- SHOW=true
- USER_INPUT
```
When both env_file and environment are set for a service, values set by environment have precedence.
### `healthcheck`
`healthcheck` declares a check that's run to determine whether or not the service containers are "healthy". It works in the same way, and has the same default values, as the HEALTHCHECK Dockerfile instruction
set by the service's [Docker](Docker.md) image. Your Compose file can override the values set in the Dockerfile.
```yaml
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 1m30s
timeout: 10s
retries: 3
start_period: 40s
start_interval: 5s
```
### `image`
`image` specifies the image to start the container from. image must follow the Open Container Specification addressable image format, as `[<registry>/][<project>/]<image>[:<tag>|@<digest>`.
```yaml
image: redis
image: redis:5
image: redis@sha256:0ed5d5928d4737458944eb604cc8509e245c3e19d02ad83935398bc4b991aac7
image: library/redis
image: docker.io/library/redis
image: my_private.registry:5000/redis
```
### `labels`
`labels` add metadata to containers. You can use either an array or a map.
It's recommended that you use reverse-[DNS](../internet/DNS.md) notation to prevent your labels from conflicting with those used by other software.
```yaml
labels:
com.example.description: "Accounting webapp"
com.example.department: "Finance"
com.example.label-with-empty-value: ""
labels:
- "com.example.description=Accounting webapp"
- "com.example.department=Finance"
- "com.example.label-with-empty-value"
```
### `network_mode`
`network_mode` sets a service container's network mode. Available values are platform specific, but Compose defines specific values which must be implemented as described if supported:
- `none`: Turns off all container networking.
- `host`: Gives the container raw access to the host's network interface.
- `service:{name}`: Gives the containers access to the specified service only.
```yaml
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
```
When set, the `networks` attribute is not allowed and Compose rejects any Compose file containing both attributes.
### `networks`
`networks` defines the networks that service containers are attached to, referencing entries under the top-level networks key.
```yaml
services:
some-service:
networks:
- some-network
- other-network
```
### `ports`
Exposes container ports.
The short syntax is a colon-separated string to set the host IP, host port, and container port in the form:
`[HOST:]CONTAINER[/PROTOCOL]` where:
- `HOST` is `[IP:](port | range)`
- `CONTAINER` is `port | range`
- `PROTOCOL` to restrict port to specified protocol. [tcp](../internet/TCP.md) and [udp](../internet/UDP.md) values are defined by the Specification.
If host IP is not set, it binds to all network interfaces. Ports can be either a single value or a range. Host and container must use equivalent ranges.
Either specify both ports `(HOST:CONTAINER)`, or just the container port. In the latter case, Compose automatically allocates any unassigned port of the host.
`HOST:CONTAINER` should always be specified as a (quoted) string, to avoid conflicts with yaml base-60 float
```yaml
ports:
- "3000"
- "3000-3005"
- "8000:8000"
- "9090-9091:8080-8081"
- "49100:22"
- "8000-9000:80"
- "127.0.0.1:8001:8001"
- "127.0.0.1:5000-5010:5000-5010"
- "6060:6060/udp"
```
### `privileged`
`privileged` configures the service container to run with elevated privileges.
### `restart`
`restart` defines the policy that the platform applies on container termination.
- `no`: The default restart policy. It does not restart the container under any circumstances.
- `always`: The policy always restarts the container until its removal.
- `on-failure`: The policy restarts the container if the exit code indicates an error.
- `unless-stopped`: The policy restarts the container irrespective of the exit code but stops restarting when the service is stopped or removed.
```yaml
restart: "no"
restart: always
restart: on-failure
restart: unless-stopped
```
### `secrets`
`secrets` grants access to sensitive data defined by secrets on a per-service basis. Two different syntax variants are supported; the short syntax and the long syntax.
Compose reports an error if the secret doesn't exist on the platform or isn't defined in the secrets section of the Compose file.
Services can be granted access to multiple secrets. Long and short syntax for secrets may be used in the same Compose file. Defining a secret in the top-level secrets must not imply granting any service access to it. Such grant must be explicit within service specification as secrets service element.
The short syntax variant only specifies the secret name. This grants the container access to the secret and mounts it as read-only to `/run/secrets/<secret_name>` within the container. The source name and destination mountpoint are both set to the secret name.
The following example uses the short syntax to grant the frontend service access to the server-certificate secret. The value of server-certificate is set to the contents of the file `./server.cert`.
```yaml
services:
frontend:
image: example/webapp
secrets:
- server-certificate
secrets:
server-certificate:
file: ./server.cert
```
The long syntax provides more granularity in how the secret is created within the service's containers.
- `source`: The name of the secret as it exists on the platform.
- `target`: The name of the file to be mounted in `/run/secrets/` in the service's task container, or absolute path of the file if an alternate location is required. Defaults to source if not specified.
- `uid` and `gid`: The numeric UID or GID that owns the file within `/run/secrets/` in the service's task containers. Default value is USER running container.
- `mode`: The permissions for the file to be mounted in `/run/secrets/` in the service's task containers, in octal notation. The default value is world-readable permissions (mode `0444`). The writable bit must be ignored if set. The executable bit may be set.
The following example sets the name of the server-certificate secret file to server.crt within the container, sets the mode to 0440 (group-readable), and sets the user and group to 103. The value of server-certificate secret is provided by the platform through a lookup and the secret's lifecycle is not directly managed by Compose.
```yaml
services:
frontend:
image: example/webapp
secrets:
- source: server-certificate
target: server.cert
uid: "103"
gid: "103"
mode: 0440
secrets:
server-certificate:
external: true
```
### `volumes`
`volumes` define mount host paths or named volumes that are accessible by service containers. You can use `volumes` to define multiple types of mounts; `volume`, `bind`, `tmpfs`, or `npipe`.
The short syntax uses a single string with colon-separated values to specify a volume mount `(VOLUME:CONTAINER_PATH)`, or an access mode `(VOLUME:CONTAINER_PATH:ACCESS_MODE)`.
- `VOLUME`: Can be either a host path on the platform hosting containers (bind mount) or a volume name.
- `CONTAINER_PATH`: The path in the container where the volume is mounted.
- `ACCESS_MODE`: A comma-separated , list of options:
- - `rw`: Read and write access. This is the default if none is specified.
- - `ro`: Read-only access.
```yaml
volumes:
- ./volume:/mnt
```
## Secrets
The top-level secrets declaration defines or references sensitive data that is granted to the services in your Compose application. The source of the secret is either file or environment.
- `file`: The secret is created with the contents of the file at the specified path.
- `environment`: The secret is created with the value of an environment variable.
- `external`: If set to true, external specifies that this secret has already been created. Compose does not attempt to create it, and if it does not exist, an error occurs.
```yaml
secrets:
server-certificate:
file: ./server.cert
```
## Docker Compose Deploy
The Compose Deploy Specification lets you declare additional metadata on services so Compose gets relevant data to allocate adequate resources on the platform and configure them to match your needs.
### `mode`
`mode` defines the replication model used to run the service on the platform. Either `global`, exactly one container per physical node, or `replicated`, a specified number of containers. The default is `replicated`.
```yaml
services:
frontend:
image: example/webapp
deploy:
mode: global
```
### `replicas`
If the service is `replicated` (which is the default), `replicas` specifies the number of containers that should be running at any given time.
```yaml
services:
frontend:
image: example/webapp
deploy:
mode: replicated
replicas: 6
```
### `restart_policy`
`restart_policy` configures if and how to restart containers when they exit. If `restart_policy` is not set, Compose considers the restart field set by the service configuration.
- `condition`. When set to:
- - `none`, containers are not automatically restarted regardless of the exit status.
- - `on-failure`, the container is restarted if it exits due to an error, which manifests as a non-zero exit code.
- - `any` (default), containers are restarted regardless of the exit status.
- `delay`: How long to wait between restart attempts, specified as a duration. The default is 0, meaning restart attempts can occur immediately.
- `max_attempts`: How many times to attempt to restart a container before giving up (default: never give up). If the restart does not succeed within the configured `window`, this attempt doesn't count toward the configured `max_attempts` value. For example, if `max_attempts` is set to '2', and the restart fails on the first attempt, more than two restarts must be attempted.
- `window`: How long to wait before deciding if a restart has succeeded, specified as a duration (default: decide immediately).
```yaml
deploy:
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 120s
```
### `placement`
`placement` specifies constraints and preferences for the platform to select a physical node to run service containers.
constraints
`constraints` defines a required property the platform's node must fulfill to run the service container. It can be set either by a list or a map with string values.
```yaml
deploy:
placement:
constraints:
- disktype=ssd
```
```yaml
deploy:
placement:
constraints:
disktype: ssd
```
`preferences` defines a property the platform's node should fulfill to run service container. It can be set either by a list or a map with string values.
```yaml
deploy:
placement:
preferences:
- datacenter=us-east
```
```yaml
deploy:
placement:
preferences:
datacenter: us-east
```

105
technology/tools/Docker.md Normal file
View file

@ -0,0 +1,105 @@
---
website: https://www.docker.com/
obj: application
---
#refactor
---
Notes:
- Docker (CLI)
- Dockerfile
- Docker Swarm
---
# Docker
[Docker](https://www.docker.com/) is a utility to pack, ship and run any application as a lightweight container. Another container engine is [Podman](Podman.md)
## Dockerfile
Every container can be build from a `Dockerfile`.
### Example
A sample `Dockerfile`:
```dockerfile
FROM node:12-alpine
RUN apk add --no-cache python2 g++ make
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]
EXPOSE 3000
```
`FROM` defines the base image the container builds upon.
`RUN` runs a specific command.
`WORKDIR` changes working directory.
`COPY` copies files into the container image.
`CMD` is run when the container starts.
`EXPOSE` exposes a port to the network.
`ENV` sets environment variables
`ENTRYPOINT` specifies the executable that will run when the container starts
`ARG` defines build-time variables that can be passed to the `docker build` command with the `--build-arg` flag
To build a `Dockerfile`:
```shell
docker build -t getting-started .
```
## Docker Compose
[Docker Compose](https://docs.docker.com/compose/) is an alternate CLI frontend for the Docker Engine, which specifies properties of containers using a `docker-compose.yml` YAML file rather than, for example, a script with `docker run` options. This is useful for setting up reoccuring services that are use often and/or have complex configurations.
### Example
```yaml
version: "3.7"
services:
app:
build: ./app
ports:
- 3000:3000
volumes:
- ./:/app
environment:
MYSQL_HOST: mysql
MYSQL_USER: root
MYSQL_PASSWORD: secret
MYSQL_DB: todos
mysql:
image: mysql:5.7
volumes:
- todo-mysql-data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: todos
```
Every container is defined within the `services`.
Ports Forwards and Volumes are defined in their respective `ports` and `volumes`.
Everything inside `environment` is passed as a environment variable.
Containers can use a prebuild image (`image: image:tag`) or build one from scratch (`build: ./dir`)
### Usage
```shell
docker-compose -f docker-compose.yml up # Start services
docker-compose -f docker-compose.yml down # Stop services
docker-compose -f docker-compose.yml build # Rebuild services
docker-compose -f docker-compose.yml pull # Pull images
```
## Docker Swarm
Current versions of Docker include _swarm mode_ for natively managing a cluster of Docker Engines called a _swarm_. Use the Docker CLI to create a swarm, deploy application services to a swarm, and manage swarm behavior.
### Usage
```shell
# Create a swarm
docker swarm init --advertise-addr <MANAGER-IP>
# Get a join command on manager
docker swarm join-token worker
# Join a swarm
docker swarm join --token <TOKEN> <MANAGER-IP>:2377
# View node info
docker node ls
```

69
technology/tools/GPG.md Normal file
View file

@ -0,0 +1,69 @@
---
aliases: ["PGP", "GnuPG", "OpenPGP"]
website: https://www.gnupg.org/
obj: application
---
# GPG
gpg is the OpenPGP part of the GNU Privacy Guard (GnuPG). It is a tool to provide digital encryption and signing services using the OpenPGP standard. gpg features complete key management and all the bells and whistles you would expect from a full OpenPGP implementation.
#refactor add options + refactor
## Commands
**Sign:**
```shell
gpg --sign
gpg -s
gpg --clear-sign # Sign with clear text
```
**Encrypt:**
```shell
gpg --encrypt
gpg -e
```
**Symmetric Encryption:**
```shell
gpg --symmetric
gpg -c
```
**Decrypt:**
```shell
gpg --decrypt
gpg -d
```
**Verify:**
```shell
gpg --verify
```
## Keys
**List keys:**
```shell
gpg --list-keys
gpg -k # List public keys
gpg -K # List private keys
```
**Generate key:**
```shell
gpg --generate-key
```
**Import & export keys:**
```shell
gpg --export
gpg --import
```
**Key selection:**
```shell
 -r, --recipient KEY # Encrypt for key
 -u, --local-user KEY # Use this key
```

44
technology/tools/I2P.md Normal file
View file

@ -0,0 +1,44 @@
---
website: https://geti2p.net/de/
obj: application
repo: https://github.com/PurpleI2P/i2pd
---
#refactor
# I2P Network
I2P is an anonymizing network, offering a simple layer that identity-sensitive applications can use to securely communicate. All data is wrapped with several layers of encryption, and the network is both distributed and dynamic, with no trusted parties. Many applications are available that interface with I2P, including mail, peer-peer, IRC chat, and others. Anonymous [Torrenting](BitTorrent.md) via i2psnark is also possible.
## Usage
Install `i2pd` (deamon written in C++) and enable the service. Router Interface is at `127.0.0.1:7070` with [HTTP](../internet/HTTP.md) Proxy at `127.0.0.1:4444`
## Tunnel Configuration
### Client Tunnel
Expose a i2p service on client port
```
[client]
type = client
address = 127.0.0.1
port = 6668
destination = client.i2p
keys = client.dat
```
### Server Tunnel
Expose a generic service as i2p service:
```
[server]
type = server
host = 127.0.0.1
port = 25
keys = server.dat
```
### [HTTP](../internet/HTTP.md) Tunnel (Website)
Run a web server:
```
[http-server]
type = http
host = 127.0.0.1
port = 80
keys = our-website.dat
```

View file

@ -0,0 +1,479 @@
---
obj: concept
website: https://json-schema.org
---
# JSON Schema
JSON Schema is a schema specification for [JSON](../files/JSON.md), which can validate a [JSON](../files/JSON.md) Document to be of a specific format.
## `type` Keyword
The `type` keyword is used to restrict the types of a property
```json
{ "type": "string" }
````
Every type has specific keywords that can be used:
### `string`
#### Length
The length of a string can be constrained:
```json
{
"type": "string",
"minLength": 2,
"maxLength": 3
}
```
#### [Regex](Regex.md)
The `pattern` keyword is used to restrict a string to a particular [regular expression](Regex.md)
```json
{
"type": "string",
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}
```
#### Format
The format keyword allows for basic semantic identification of certain kinds of string values that are commonly used. For example, because [JSON](../files/JSON.md) doesn't have a "DateTime" type, dates need to be encoded as strings. format allows the schema author to indicate that the string value should be interpreted as a date. By default, format is just an annotation and does not effect validation.
Optionally, validator implementations can provide a configuration option to enable format to function as an assertion rather than just an annotation. That means that validation will fail if, for example, a value with a date format isn't in a form that can be parsed as a date. This can allow values to be constrained beyond what the other tools in JSON Schema, including Regular Expressions can do.
##### Built-in formats
The following is the list of formats specified in the JSON Schema specification.
###### Dates and times
Dates and times are represented in [RFC 3339, section 5.6](https://tools.ietf.org/html/rfc3339#section-5.6). This is a subset of the date format also commonly known as [ISO8601 format](https://www.iso.org/iso-8601-date-and-time-format.html).
- `"date-time"`: Date and time together, for example, `2018-11-13T20:20:39+00:00`.
- `"time"`: Time, for example, `20:20:39+00:00`
- `"date"`: Date, for example, `2018-11-13`.
- `"duration"`: A duration as defined by the [ISO 8601 ABNF for "duration"](https://datatracker.ietf.org/doc/html/rfc3339#appendix-A). For example, `P3D` expresses a duration of 3 days.
###### [Email](../internet/eMail.md) addresses
- `"email"`: Internet email address, see [RFC 5321, section 4.1.2](http://tools.ietf.org/html/rfc5321#section-4.1.2).
- `"idn-email"`: The internationalized form of an Internet email address, see [RFC 6531](https://tools.ietf.org/html/rfc6531).
###### Hostnames
- `"hostname"`: Internet host name, see [RFC 1123, section 2.1](https://datatracker.ietf.org/doc/html/rfc1123#section-2.1).
- `"idn-hostname"`: An internationalized Internet host name, see [RFC5890, section 2.3.2.3](https://tools.ietf.org/html/rfc5890#section-2.3.2.3).
###### IP Addresses
- `"ipv4"`: IPv4 address, according to dotted-quad ABNF syntax as defined in [RFC 2673, section 3.2](http://tools.ietf.org/html/rfc2673#section-3.2).
- `"ipv6"`: IPv6 address, as defined in [RFC 2373, section 2.2](http://tools.ietf.org/html/rfc2373#section-2.2).
###### Resource identifiers
- `"uuid"`: A Universally Unique Identifier as defined by [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122). Example: `3e4666bf-d5e5-4aa7-b8ce-cefe41c7568a`
- `"uri"`: A universal resource identifier (URI), according to [RFC3986](http://tools.ietf.org/html/rfc3986).
- `"uri-reference"`: A URI Reference (either a URI or a relative-reference), according to [RFC3986, section 4.1](http://tools.ietf.org/html/rfc3986#section-4.1).
- `"iri"`: The internationalized equivalent of a "uri", according to [RFC3987](https://tools.ietf.org/html/rfc3987).
- `"iri-reference"`: New in draft 7The internationalized equivalent of a "uri-reference", according to [RFC3987](https://tools.ietf.org/html/rfc3987)
If the values in the schema have the ability to be relative to a particular source path (such as a link from a webpage), it is generally better practice to use `"uri-reference"` (or `"iri-reference"`) rather than `"uri"` (or `"iri"`). `"uri"` should only be used when the path must be absolute.
###### URI template
- `"uri-template"`: A URI Template (of any level) according to [RFC6570](https://tools.ietf.org/html/rfc6570). If you don't already know what a URI Template is, you probably don't need this value.
###### JSON Pointer
- `"json-pointer"`: A JSON Pointer, according to [RFC6901](https://tools.ietf.org/html/rfc6901). There is more discussion on the use of JSON Pointer within JSON Schema in [Structuring a complex schema](https://json-schema.org/understanding-json-schema/structuring). Note that this should be used only when the entire string contains only JSON Pointer content, e.g. `/foo/bar`. JSON Pointer URI fragments, e.g. `#/foo/bar/` should use `"uri-reference"`.
- `"relative-json-pointer"`: A [relative JSON pointer](https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01).
###### Regular Expressions
- `"regex"`: A [regular expression](Regex.md), which should be valid according to the [ECMA 262](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/) dialect.
### `integer`
The `integer` type is used for integral numbers. JSON does not have distinct types for integers and floating-point values. Therefore, the presence or absence of a decimal point is not enough to distinguish between integers and non-integers. For example, `1` and `1.0` are two ways to represent the same value in JSON. JSON Schema considers that value an integer no matter which representation was used.
For differencing float and integer values these types can be used.
```json
{ "type": "integer"}
{ "type": "number" }
```
#### Multiples
Numbers can be restricted to a multiple of a given number, using the `multipleOf` keyword. It may be set to any positive number.
```json
{
"type": "number",
"multipleOf" : 10
}
```
#### Range
Ranges of numbers are specified using a combination of the `minimum` and `maximum` keywords, (or `exclusiveMinimum` and `exclusiveMaximum` for expressing exclusive range).
```json
{
"type": "number",
"minimum": 0,
"exclusiveMaximum": 100
}
```
### `object`
Objects are the mapping type in [JSON](../files/JSON.md). They map "keys" to "values". In [JSON](../files/JSON.md), the "keys" must always be strings. Each of these pairs is conventionally referred to as a "property".
```json
{ "type": "object" }
```
#### Properties
The properties (key-value pairs) on an object are defined using the `properties` keyword. The value of `properties` is an object, where each key is the name of a property and each value is a schema used to validate that property. Any property that doesn't match any of the property names in the `properties` keyword is ignored by this keyword.
```json
{
"type": "object",
"properties": {
"number": { "type": "number" },
"street_name": { "type": "string" },
"street_type": { "enum": ["Street", "Avenue", "Boulevard"] }
}
}
```
#### Pattern Properties
Sometimes you want to say that, given a particular kind of property name, the value should match a particular schema. That's where `patternProperties` comes in: it maps regular expressions to schemas. If a property name matches the given [regular expression](Regex.md), the property value must validate against the corresponding schema.
```json
{
"type": "object",
"patternProperties": {
"^S_": { "type": "string" },
"^I_": { "type": "integer" }
}
}
```
#### Additional Properties
The `additionalProperties` keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the `properties` keyword or match any of the regular expressions in the `patternProperties` keyword. By default any additional properties are allowed.
The value of the `additionalProperties` keyword is a schema that will be used to validate any properties in the instance that are not matched by `properties` or `patternProperties`. Setting the `additionalProperties` schema to `false` means no additional properties will be allowed.
```json
{
"type": "object",
"properties": {
"number": { "type": "number" },
"street_name": { "type": "string" },
"street_type": { "enum": ["Street", "Avenue", "Boulevard"] }
},
"additionalProperties": false
}
```
#### Required Properties
By default, the properties defined by the `properties` keyword are not required. However, one can provide a list of required properties using the `required` keyword.
```json
{
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" },
"address": { "type": "string" },
"telephone": { "type": "string" }
},
"required": ["name", "email"]
}
```
#### Property names
The names of properties can be validated against a schema, irrespective of their values. This can be useful if you don't want to enforce specific properties, but you want to make sure that the names of those properties follow a specific convention. You might, for example, want to enforce that all names are valid [ASCII](../files/ASCII.md) tokens so they can be used as attributes in a particular programming language.
```json
{
"type": "object",
"propertyNames": {
"pattern": "^[A-Za-z_][A-Za-z0-9_]*$"
}
}
```
#### Size
The number of properties on an object can be restricted using the `minProperties` and `maxProperties` keywords. Each of these must be a non-negative integer.
```json
{
"type": "object",
"minProperties": 2,
"maxProperties": 3
}
```
### `array`
Arrays are used for ordered elements. In [JSON](../files/JSON.md), each element in an array may be of a different type.
```json
{ "type": "array" }
```
#### Items
List validation is useful for arrays of arbitrary length where each item matches the same schema. For this kind of array, set the `items` keyword to a single schema that will be used to validate all of the items in the array.
```json
{
"type": "array",
"items": {
"type": "number"
}
}
```
#### Tuple Validation
Tuple validation is useful when the array is a collection of items where each has a different schema and the ordinal index of each item is meaningful.
```json
{
"type": "array",
"prefixItems": [
{ "type": "number" },
{ "type": "string" },
{ "enum": ["Street", "Avenue", "Boulevard"] },
{ "enum": ["NW", "NE", "SW", "SE"] }
]
}
```
#### Additional Items
The `items` keyword can be used to control whether it's valid to have additional items in a tuple beyond what is defined in `prefixItems`. The value of the `items` keyword is a schema that all additional items must pass in order for the keyword to validate.
```json
{
"type": "array",
"prefixItems": [
{ "type": "number" },
{ "type": "string" },
{ "enum": ["Street", "Avenue", "Boulevard"] },
{ "enum": ["NW", "NE", "SW", "SE"] }
],
"items": false
}
```
#### Unevaluated Items
The `unevaluatedItems` keyword is useful mainly when you want to add or disallow extra items to an array.
`unevaluatedItems` applies to any values not evaluated by an `items`, `prefixItems`, or `contains` keyword. Just as `unevaluatedProperties` affects only **properties** in an object, `unevaluatedItems` affects only **items** in an array.
Watch out! The word "unevaluated" _does not mean_ "not evaluated by `items`, `prefixItems`, or `contains`." "Unevaluated" means "not successfully evaluated", or "does not evaluate to true".
Like with `items`, if you set `unevaluatedItems` to `false`, you can disallow extra items in the array.
```json
{
"prefixItems": [
{ "type": "string" }, { "type": "number" }
],
"unevaluatedItems": false
}
```
#### Contains
While the `items` schema must be valid for every item in the array, the `contains` schema only needs to validate against one or more items in the array.
```json
{
"type": "array",
"contains": {
"type": "number"
}
}
```
#### minContains / maxContains
`minContains` and `maxContains` can be used with `contains` to further specify how many times a schema matches a `contains` constraint. These keywords can be any non-negative number including zero.
```json
{
"type": "array",
"contains": {
"type": "number"
},
"minContains": 2,
"maxContains": 3
}
```
#### Length
The length of the array can be specified using the minItems and maxItems keywords. The value of each keyword must be a non-negative number. These keywords work whether doing list validation or tuple-validation.
```json
{
"type": "array",
"minItems": 2,
"maxItems": 3
}
```
#### Uniqueness
A schema can ensure that each of the items in an array is unique. Simply set the `uniqueItems` keyword to `true`.
```json
{
"type": "array",
"uniqueItems": true
}
```
### `boolean`
The boolean type matches only two special values: `true` and `false`. Note that values that _evaluate_ to `true` or `false`, such as 1 and 0, are not accepted by the schema.
```json
{ "type": "boolean" }
```
### `null`
When a schema specifies a type of null, it has only one acceptable value: null.
```json
{ "type": "null" }
```
## Annotations
JSON Schema includes a few keywords, that aren't strictly used for validation, but are used to describe parts of a schema. None of these "annotation" keywords are required, but they are encouraged for good practice, and can make your schema "self-documenting".
The `title` and `description` keywords must be strings. A "title" will preferably be short, whereas a "description" will provide a more lengthy explanation about the purpose of the data described by the schema.
The `default` keyword specifies a default value. This value is not used to fill in missing values during the validation process. Non-validation tools such as documentation generators or form generators may use this value to give hints to users about how to use a value. However, `default` is typically used to express that if a value is missing, then the value is semantically the same as if the value was present with the default value. The value of `default` should validate against the schema in which it resides, but that isn't required.
The `examples` keyword is a place to provide an array of examples that validate against the schema. This isn't used for validation, but may help with explaining the effect and purpose of the schema to a reader. Each entry should validate against the schema in which it resides, but that isn't strictly required. There is no need to duplicate the `default` value in the `examples` array, since `default` will be treated as another example.
The boolean keywords `readOnly` and `writeOnly` are typically used in an API context. `readOnly` indicates that a value should not be modified. It could be used to indicate that a `PUT` request that changes a value would result in a `400 Bad Request` response. `writeOnly` indicates that a value may be set, but will remain hidden. In could be used to indicate you can set a value with a `PUT` request, but it would not be included when retrieving that record with a `GET` request.
The `deprecated` keyword is a boolean that indicates that the instance value the keyword applies to should not be used and may be removed in the future.
```json
{
"title": "Match anything",
"description": "This is a schema that matches anything.",
"default": "Default value",
"examples": [
"Anything",
4035
],
"deprecated": true,
"readOnly": true,
"writeOnly": false
}
```
## Enumerated values
The `enum` keyword is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique.
```json
{
"enum": ["red", "amber", "green"]
}
```
## Constant Values
The `const` keyword is used to restrict a value to a single value.
```json
{
"properties": {
"country": {
"const": "United States of America"
}
}
}
```
## Media: string-encoding non [JSON](../files/JSON.md) Data
JSON schema has a set of keywords to describe and optionally validate non-JSON data stored inside [JSON](../files/JSON.md) strings. Since it would be difficult to write validators for many media types, JSON schema validators are not required to validate the contents of [JSON](../files/JSON.md) strings based on these keywords. However, these keywords are still useful for an application that consumes validated [JSON](../files/JSON.md).
### contentMediaType
The `contentMediaType` keyword specifies the [MIME](../files/MIME.md) type of the contents of a string, as described in [RFC 2046](https://tools.ietf.org/html/rfc2046). There is a list of [MIME types officially registered by the IANA](http://www.iana.org/assignments/media-types/media-types.xhtml), but the set of types supported will be application and operating system dependent. Mozilla Developer Network also maintains a [shorter list of MIME types that are important for the web](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types)
### contentEncoding
The `contentEncoding` keyword specifies the encoding used to store the contents, as specified in [RFC 2054, part 6.1](https://tools.ietf.org/html/rfc2045) and [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648).
The acceptable values are `7bit`, `8bit`, `binary`, `quoted-printable`, `base16`, `base32`, and `base64`. If not specified, the encoding is the same as the containing [JSON](../files/JSON.md) document.
Without getting into the low-level details of each of these encodings, there are really only two options useful for modern usage:
- If the content is encoded in the same encoding as the enclosing [JSON](../files/JSON.md) document (which for practical purposes, is almost always UTF-8), leave `contentEncoding` unspecified, and include the content in a string as-is. This includes text-based content types, such as `text/html` or `application/xml`.
- If the content is binary data, set `contentEncoding` to `base64` and encode the contents using [Base64](https://tools.ietf.org/html/rfc4648). This would include many image types, such as `image/png` or audio types, such as `audio/mpeg`.
```json
{
"type": "string",
"contentMediaType": "text/html"
}
```
```json
{
"type": "string",
"contentEncoding": "base64",
"contentMediaType": "image/png"
}
```
## Conditional Schemas
### dependentRequired
The `dependentRequired` keyword conditionally requires that certain properties must be present if a given property is present in an object. For example, suppose we have a schema representing a customer. If you have their credit card number, you also want to ensure you have a billing address. If you don't have their credit card number, a billing address would not be required. We represent this dependency of one property on another using the `dependentRequired` keyword. The value of the `dependentRequired` keyword is an object. Each entry in the object maps from the name of a property, _p_, to an array of strings listing properties that are required if _p_ is present.
```json
{
"type": "object",
"properties": {
"name": { "type": "string" },
"credit_card": { "type": "number" },
"billing_address": { "type": "string" }
},
"required": ["name"],
"dependentRequired": {
"credit_card": ["billing_address"]
}
}
```
### dependentSchemas
The `dependentSchemas` keyword conditionally applies a subschema when a given property is present. This schema is applied in the same way [allOf](https://json-schema.org/understanding-json-schema/reference/combining#allof) applies schemas. Nothing is merged or extended. Both schemas apply independently.
```json
{
"type": "object",
"properties": {
"name": { "type": "string" },
"credit_card": { "type": "number" }
},
"required": ["name"],
"dependentSchemas": {
"credit_card": {
"properties": {
"billing_address": { "type": "string" }
},
"required": ["billing_address"]
}
}
}
```
### If-Then-Else
The if, then and else keywords allow the application of a subschema based on the outcome of another schema, much like the if/then/else constructs you've probably seen in traditional programming languages.
```json
{
"type": "object",
"properties": {
"street_address": {
"type": "string"
},
"country": {
"default": "United States of America",
"enum": ["United States of America", "Canada"]
}
},
"if": {
"properties": { "country": { "const": "United States of America" } }
},
"then": {
"properties": { "postal_code": { "pattern": "[0-9]{5}(-[0-9]{4})?" } }
},
"else": {
"properties": { "postal_code": { "pattern": "[A-Z][0-9][A-Z] [0-9][A-Z][0-9]" } }
}
}
```

View file

@ -0,0 +1,106 @@
---
obj: concept
website: https://jsonpatch.com
rfc: https://datatracker.ietf.org/doc/html/rfc6902
---
# JSONPatch
JSON Patch is a format for describing changes to a [JSON](../files/JSON.md) document. It can be used to avoid sending a whole document when only a part has changed. When used in combination with the [HTTP](../internet/HTTP.md) PATCH method, it allows partial updates for [HTTP](../internet/HTTP.md) APIs in a standards compliant way.
The patch documents are themselves [JSON](../files/JSON.md) documents.
A JSON Patch document is just a [JSON](../files/JSON.md) file containing an array of patch operations. The patch operations supported by JSON Patch are “add”, “remove”, “replace”, “move”, “copy” and “test”. The operations are applied in order: if any of them fail then the whole patch operation should abort.
## Simple example
### The original document
```json
{
"baz": "qux",
"foo": "bar"
}
```
### The patch
```json
[
{ "op": "replace", "path": "/baz", "value": "boo" },
{ "op": "add", "path": "/hello", "value": ["world"] },
{ "op": "remove", "path": "/foo" }
]
```
### The result
```json
{
"baz": "boo",
"hello": ["world"]
}
```
## JSON Pointer
JSON Pointer ([IETF RFC 6901](https://datatracker.ietf.org/doc/html/rfc6901/)) defines a string format for identifying a specific value within a [JSON](../files/JSON.md) document. It is used by all operations in JSON Patch to specify the part of the document to operate on.
A JSON Pointer is a string of tokens separated by `/` characters, these tokens either specify keys in objects or indexes into arrays. For example, given the [JSON](../files/JSON.md)
```json
{
"biscuits": [
{ "name": "Digestive" },
{ "name": "Choco Leibniz" }
]
}
```
`/biscuits` would point to the array of biscuits and `/biscuits/1/name` would point to `"Choco Leibniz"`.
To point to the root of the document use an empty string for the pointer. The pointer `/` doesnt point to the root, it points to a key of `""` on the root (which is totally valid in [JSON](../files/JSON.md)).
If you need to refer to a key with `~` or `/` in its name, you must escape the characters with `~0` and `~1` respectively. For example, to get `"baz"` from `{ "foo/bar~": "baz" }` youd use the pointer `/foo~1bar~0`.
Finally, if you need to refer to the end of an array you can use `-` instead of an index. For example, to refer to the end of the array of biscuits above you would use `/biscuits/-`. This is useful when you need to insert a value at the end of an array.
## Operations
### Add
```json
{ "op": "add", "path": "/biscuits/1", "value": { "name": "Ginger Nut" } }
```
Adds a value to an object or inserts it into an array. In the case of an array, the value is inserted before the given index. The `-` character can be used instead of an index to insert at the end of an array.
### Remove
```json
{ "op": "remove", "path": "/biscuits" }
```
Removes a value from an object or array.
```json
{ "op": "remove", "path": "/biscuits/0" }
```
Removes the first element of the array at `biscuits` (or just removes the “0” key if `biscuits` is an object)
### Replace
```json
{ "op": "replace", "path": "/biscuits/0/name", "value": "Chocolate Digestive" }
```
Replaces a value. Equivalent to a "remove" followed by an "add".
### Copy
```json
{ "op": "copy", "from": "/biscuits/0", "path": "/best_biscuit" }
```
Copies a value from one location to another within the [JSON](../files/JSON.md) document. Both `from` and `path` are JSON Pointers.
### Move
```json
{ "op": "move", "from": "/biscuits", "path": "/cookies" }
```
Moves a value from one location to the other. Both `from` and `path` are JSON Pointers.
### Test
```json
{ "op": "test", "path": "/best_biscuit/name", "value": "Choco Leibniz" }
```
Tests that the specified value is set in the document. If the test fails, then the patch as a whole should not apply.

431
technology/tools/Jinja.md Normal file
View file

@ -0,0 +1,431 @@
---
obj: concept
wiki: https://en.wikipedia.org/wiki/Jinja_(template_engine)
website: https://jinja.palletsprojects.com/en/3.1.x
---
# Jinja Templates
Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to [Python](../programming/languages/Python.md) syntax. Then the template is passed data to render the final document. Jinja template files commonly have the `.j2` extension.
## Syntax
Below is a minimal template that illustrates a few basics using the default Jinja configuration:
```
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
{# a comment #}
</body>
</html>
```
There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:
- `{% ... %}` for Statements
- `{{ ... }}` for Expressions to print to the template output
- `{# ... #}` for Comments not included in the template output
### Comments
To comment-out part of a line in a template, use the comment syntax which is by default set to `{# ... #}`. This is useful to comment out parts of the template for debugging or to add information for other template designers or yourself:
```
{# note: commented-out template because we no longer use this
{% for user in users %}
...
{% endfor %}
#}
```
### Expressions
Jinja allows basic expressions everywhere. These work very similarly to regular [Python](../programming/languages/Python.md); even if youre not working with [Python](../programming/languages/Python.md) you should feel comfortable with it.
#### Literals
The simplest form of expressions are literals. Literals are representations for [Python](../programming/languages/Python.md) objects such as strings and numbers. The following literals exist:
`"Hello World"`
Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (e.g. as arguments to function calls and filters, or just to extend or include a template).
`42` / `123_456`
Integers are whole numbers without a decimal part. The _ character can be used to separate groups for legibility.
`42.23` / `42.1e2` / `123_456.789`
Floating point numbers can be written using a . as a decimal mark. They can also be written in scientific notation with an upper or lower case e to indicate the exponent part. The _ character can be used to separate groups for legibility, but cannot be used in the exponent part.
`['list', 'of', 'objects']`
Everything between two brackets is a list. Lists are useful for storing sequential data to be iterated over. For example, you can easily create a list of links using lists and tuples for (and with) a for loop:
```
<ul>
{% for href, caption in [('index.html', 'Index'), ('about.html', 'About'),
('downloads.html', 'Downloads')] %}
<li><a href="{{ href }}">{{ caption }}</a></li>
{% endfor %}
</ul>
```
`('tuple', 'of', 'values')`
Tuples are like lists that cannot be modified (“immutable”). If a tuple only has one item, it must be followed by a comma (`('1-tuple',)`). Tuples are usually used to represent items of two or more elements. See the list example above for more details.
`{'dict': 'of', 'key': 'and', 'value': 'pairs'}`
A dict in [Python](../programming/languages/Python.md) is a structure that combines keys and values. Keys must be unique and always have exactly one value. Dicts are rarely used in templates; they are useful in some rare cases such as the `xmlattr()` filter.
`true` / `false`
`true` is always true and `false` is always false.
#### If Expression
It is also possible to use inline if expressions. These are useful in some situations. For example, you can use this to extend from one template if a variable is defined, otherwise from the default layout template:
```
{% extends layout_template if layout_template is defined else 'default.html' %}
```
The general syntax is `<do something> if <something is true> else <do something else>`.
The else part is optional. If not provided, the else block implicitly evaluates into an `Undefined` object (regardless of what `undefined` in the environment is set to):
```
{{ "[{}]".format(page.title) if page.title }}
```
#### Builtin Filters
##### batch(value, linecount: int, fill_with: 'Optional' = None)
A filter that batches items. It works pretty much like slice just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example:
```
<table>
{%- for row in items|batch(3, '&nbsp;') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
```
##### center(value, width: int = 80)
Centers the value in a field of a given width.
##### default(value, default_value, boolean: bool = False)
If the value is undefined it will return the passed default value, otherwise the value of the variable:
```
{{ my_variable|default('my_variable is not defined') }}
```
This will output the value of `my_variable` if the variable was defined, otherwise `'my_variable is not defined'`. If you want to use default with variables that evaluate to false you have to set the second parameter to true:
```
{{ ''|default('the string was empty', true) }}
```
##### dictsort(value, case_sensitive: bool = False, by: Literal\["key", "value"]' = 'key', reverse: bool = False)
Sort a dict and yield (key, value) pairs. [Python](../programming/languages/Python.md) dicts may not be in the order you want to display them in, so sort them first.
```
{% for key, value in mydict|dictsort %}
sort the dict by key, case insensitive
{% for key, value in mydict|dictsort(reverse=true) %}
sort the dict by key, case insensitive, reverse order
{% for key, value in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for key, value in mydict|dictsort(false, 'value') %}
sort the dict by value, case insensitive
```
##### escape(value)
Replace the characters `&`, `<`, `>`, `'`, and `"` in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in [HTML](../internet/HTML.md).
If the object has an `__html__` method, it is called and the return value is assumed to already be safe for [HTML](../internet/HTML.md).
##### filesizeformat(value, binary: bool = False)
Format the value like a human-readable file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to True the binary prefixes are used (Mebi, Gibi).
##### first(seq)
Return the first item of a sequence.
##### float(value, default: float = 0.0)
Convert the value into a floating point number. If the conversion doesnt work it will return `0.0`. You can override this default using the first parameter.
##### forceescape(value)
Enforce [HTML](../internet/HTML.md) escaping. This will probably double escape variables.
##### format(value, args...)
Apply the given values to a printf-style format string, like string % values.
```
{{ "%s, %s!"|format(greeting, name) }}
Hello, World!
```
In most cases it should be more convenient and efficient to use the `%` operator or `str.format()`.
```
{{ "%s, %s!" % (greeting, name) }}
{{ "{}, {}!".format(greeting, name) }}
```
##### groupby(value, attribute: str | int, default: Any | None = None, case_sensitive: bool = False)
Group a sequence of objects by an attribute using [Python](../programming/languages/Python.md)s `itertools.groupby()`. The attribute can use dot notation for nested access, like `"address.city"`. Unlike [Python](../programming/languages/Python.md)s `groupby`, the values are sorted first so only one group is returned for each unique value.
For example, a list of `User` objects with a `city` attribute can be rendered in groups. In this example, `grouper` refers to the `city` value of the group.
```
<ul>{% for city, items in users|groupby("city") %}
<li>{{ city }}
<ul>{% for user in items %}
<li>{{ user.name }}
{% endfor %}</ul>
</li>
{% endfor %}</ul>
```
`groupby` yields namedtuples of `(grouper, list)`, which can be used instead of the tuple unpacking above. `grouper` is the value of the attribute, and `list` is the items with that value.
```
<ul>{% for group in users|groupby("city") %}
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
{% endfor %}</ul>
```
You can specify a `default` value to use if an object in the list does not have the given attribute.
```
<ul>{% for city, items in users|groupby("city", default="NY") %}
<li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
{% endfor %}</ul>
```
##### indent(s: str, width: int | str = 4, first: bool = False, blank: bool = False)
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.
Parameters:
- **width**  Number of spaces, or a string, to indent by.
- **first**  Dont skip indenting the first line.
- **blank**  Dont skip indenting empty lines.
##### items(value)
Return an iterator over the `(key, value)` items of a mapping.
`x|items` is the same as `x.items()`, except if `x` is undefined an empty iterator is returned.
This filter is useful if you expect the template to be rendered with an implementation of Jinja in another programming language that does not have a `.items()` method on its mapping type.
```
<dl>
{% for key, value in my_dict|items %}
<dt>{{ key }}
<dd>{{ value }}
{% endfor %}
</dl>
```
##### join(value, d: str = '', attribute: str | int | NoneType = None)
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter:
```
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
```
##### last(seq)
Return the last item of a sequence.
##### length(obj)
Return the number of items in a container.
##### max(value)
Return the largest item from the sequence.
```
{{ [1, 2, 3]|max }}
-> 3
```
##### min(value)
Return the smallest item from the sequence.
```
{{ [1, 2, 3]|min }}
-> 1
```
##### random(seq)
Return a random item from the sequence.
##### replace(s: str, old: str, new: str, count: int | None = None)
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument `count` is given, only the first `count` occurrences are replaced:
```
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
```
##### reverse(value)
Reverse the object or return an iterator that iterates over it the other way round.
##### round(value: float, precision: int = 0, method: Literal\["common", "ceil", "floor"]' = 'common')
Round the number to a given precision. The first parameter specifies the precision (default is `0`), the second the rounding method:
- `'common'` rounds either up or down
- `'ceil'` always rounds up
- `'floor'` always rounds down
If you dont specify a method `'common'` is used.
```
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
```
Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through int:
```
{{ 42.55|round|int }}
-> 43
```
##### trim(value)
Strip leading and trailing characters, by default whitespace.
##### truncate(s: str, length: int = 255, killwords: bool = False, end: str = '...', leeway: int | None = None)
Return a truncated copy of the string. The length is specified with the first parameter which defaults to `255`. If the second parameter is `true` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (`"..."`). If you want a different ellipsis sign than `"..."` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.
```
{{ "foo bar baz qux"|truncate(9) }}
-> "foo..."
{{ "foo bar baz qux"|truncate(9, True) }}
-> "foo ba..."
{{ "foo bar baz qux"|truncate(11) }}
-> "foo bar baz qux"
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
-> "foo bar..."
```
##### unique(value, case_sensitive: bool = False, attribute: str | int | NoneType = None)
Returns a list of unique items from the given iterable.
```
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
-> ['foo', 'bar', 'foobar']
```
The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter.
Parameters:
- **case_sensitive**  Treat upper and lower case strings as distinct.
- **attribute**  Filter objects with unique values for this attribute.
##### urlencode(value)
Quote data for use in a URL path or query using UTF-8.
Basic wrapper around urllib.parse.quote() when given a string, or urllib.parse.urlencode() for a dict or iterable.
##### urlize(value)
Convert URLs in text into clickable links.
This may not recognize links in some situations. Usually, a more comprehensive formatter, such as a [Markdown](../files/Markdown.md) library, is a better choice.
##### wordcount(s: str)
Count the words in that string.
##### wordwrap(s: str, width: int = 79, break_long_words: bool = True, wrapstring: str | None = None, break_on_hyphens: bool = True)
Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately.
Parameters:
- **s**  Original text to wrap.
- **width**  Maximum length of wrapped lines.
- **break_long_words**  If a word is longer than `width`, break it across lines.
- **break_on_hyphens**  If a word contains hyphens, it may be split across lines.
- **wrapstring**  String to join each wrapped line. Defaults to `Environment.newline_sequence`.
#### Builtin Tests
##### boolean(value)
Return true if the object is a boolean value.
##### defined(value)
Return true if the variable is defined:
```
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
```
See the `default()` filter for a simple way to set undefined variables.
##### divisibleby(value, num: int)
Check if a variable is divisible by a number.
##### even(value)
Return true if the variable is even.
##### in(value, seq)
Check if `value` is in `seq`.
##### odd(value)
Return true if the variable is odd.
### Statements
#### for
Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:
```
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
</ul>
```
Inside of a for-loop block, you can access some special variables:
| Variable | Description |
| ------------------ | --------------------------------------------------------------------------------------- |
| loop.index | The current iteration of the loop. (1 indexed) |
| loop.index0 | The current iteration of the loop. (0 indexed) |
| loop.revindex | The number of iterations from the end of the loop (1 indexed) |
| loop.revindex0 | The number of iterations from the end of the loop (0 indexed) |
| loop.first | True if first iteration. |
| loop.last | True if last iteration. |
| loop.length | The number of items in the sequence. |
| loop.cycle | A helper function to cycle between a list of sequences. See the explanation below. |
| loop.depth | Indicates how deep in a recursive loop the rendering currently is. Starts at level 1 |
| loop.depth0 | Indicates how deep in a recursive loop the rendering currently is. Starts at level 0 |
| loop.previtem | The item from the previous iteration of the loop. Undefined during the first iteration. |
| loop.nextitem | The item from the following iteration of the loop. Undefined during the last iteration. |
| loop.changed(*val) | True if previously called with a different value (or not called at all). |
Within a for-loop, its possible to cycle among a list of strings/variables each time through the loop by using the special loop.cycle helper:
```
{% for row in rows %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}
```
#### if
The if statement in Jinja is comparable with the Python if statement. In the simplest form, you can use it to test if a variable is defined, not empty and not false:
```
{% if kenny.sick %}
Kenny is sick.
{% elif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
```
#### include
The `include` tag renders another template and outputs the result into the current template.
```
{% include 'header.html' %}
Body goes here.
{% include 'footer.html' %}
```

View file

@ -0,0 +1,71 @@
---
website: https://www.getmonero.org/
obj: concept
---
# Monero
Monero is a privacy-focused cryptocurrency that prioritizes anonymity and security in transactions. Launched in April 2014, Monero (XMR) has gained popularity for its commitment to providing private and untraceable transactions on a blockchain.
## Features
### 1. **Privacy and Fungibility**
Monero employs advanced cryptographic techniques, including ring signatures and stealth addresses, to ensure that transactions are private and unlinkable. This focus on privacy enhances fungibility, as all units of Monero are considered equal and indistinguishable.
### 2. **Ring Signatures**
Monero uses ring signatures to mix a user's transaction with others, making it difficult to determine the actual sender. This ensures that the true origin of funds remains confidential.
### 3. **Stealth Addresses**
Stealth addresses generate a one-time address for each transaction, making it virtually impossible to trace funds back to the recipient. This feature enhances the privacy of the receiver.
### 4. **Ring Confidential Transactions (RingCT)**
RingCT further improves privacy by concealing transaction amounts. This is achieved by allowing users to prove the validity of their transaction without revealing the exact amount involved.
### 5. **Dynamic Block Size and Fees**
Monero dynamically adjusts block size and fees based on network demand, ensuring scalability and preventing congestion.
## How Monero Works
Monero's privacy features are implemented through a combination of cryptographic techniques. When a user initiates a transaction, the following process occurs:
1. **Ring Signature Generation:**
- The sender's public key is combined with several other public keys from the blockchain to create a ring signature.
- This signature authenticates the transaction without revealing the actual sender.
2. **Stealth Address Generation:**
- The recipient's public address is masked by a one-time stealth address created for the specific transaction.
- This ensures that the recipient's identity remains private.
3. **RingCT Implementation:**
- RingCT obscures the transaction amount, providing an additional layer of privacy.
- It allows for the verification of transaction validity without disclosing specific amounts.
4. **Dynamic Block Size and Fees:**
- Monero adjusts block size and fees dynamically, allowing for scalability and preventing congestion.
## monero-cli-wallet
`monero-wallet-cli` is the wallet software shipped in the Monero archives. It is a console program, and manages an account.
Generate new wallet:
```shell
monero-wallet-cli --generate-new-wallet <file>
```
Use existing wallet:
```shell
monero-wallet-cli --wallet-file <file> --password-file <passwd>
````
### Commands
| Command | Description |
| --------------------------------------------- | ------------------------------------------------------------ |
| `wallet_info` | Show wallet main address and other info |
| `balance` | Show balance |
| `address all` | Show all addresses |
| `address new [<label>]` | Create new subaddress |
| `transfer <address> <amount>` | Send XMR to an address |
| `show_transfers [in/out/pending/failed/pool]` | Show transactions |
| `sweep_all <address>` | Send whole balance to another wallet |
| `seed` | Show secret 25 words that can be used to recover this wallet |
| `refresh` | Synchronize wallet with the Monero network |
| `status` | Check current status of wallet |
## Applications
- [Monero GUI](../applications/mobile/Monero%20GUI.md) - Official Monero GUI
- [Feather Wallet](../applications/Feather%20Wallet.md) - Open source wallet
## Sites accepting Monero
[List of supported sites](https://monerica.com/)
| Site | Description |
| ------------------------------------- | ----------- |
| [Mullvad VPN](https://mullvad.net/de) | VPN |

109
technology/tools/Podman.md Normal file
View file

@ -0,0 +1,109 @@
---
website: https://podman.io/
obj: application
repo: https://github.com/containers/podman
---
# Podman
#refactor
Podman is a rootless container engine.
# Usage
### Container Management:
1. **podman-attach**
- Description: Attach to a running container.
- Usage: `podman attach [OPTIONS] CONTAINER`
- Flags:
- `-i, --interactive`: Attach with standard input connected.
- `-t, --tty`: Allocate a pseudo-TTY.
2. **podman-container**
- Description: Manage containers.
- Usage: `podman container [SUBCOMMAND] [OPTIONS]`
- Subcommands:
- `create`: Create a new container.
- `list`: List containers.
- `inspect`: Display container configuration.
- `start`: Start one or more containers.
- `stop`: Stop one or more running containers.
- `restart`: Restart one or more containers.
- `pause`: Pause one or more containers.
- `unpause`: Unpause one or more containers.
- `kill`: Kill the main process in one or more containers.
- `rm`: Remove one or more containers.
- ... and more.
### Image Management:
1. **podman-build**
- Description: Build a container image using a Containerfile.
- Usage: `podman build [OPTIONS] PATH | URL | -`
- Flags:
- `-t, --tag`: Name and optionally a tag for the image.
2. **podman-commit**
- Description: Create a new image based on the changed container.
- Usage: `podman commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]`
- Flags:
- `--change`: Apply Dockerfile instruction to the image.
4. **podman-image**
- Description: Manage images.
- Usage: `podman image [SUBCOMMAND] [OPTIONS]`
- Subcommands:
- `list`: List images in local storage.
- `inspect`: Display image configuration.
- `remove`: Remove one or more locally stored images.
- ... and more.
5. **podman-import**
- Description: Import a tarball and save it as a filesystem image.
- Usage: `podman import [OPTIONS] FILE|- [REPOSITORY[:TAG]]`
- Flags:
- `-i, --input`: Read from specified file.
6. **podman-pull**
- Description: Pull an image from a registry.
- Usage: `podman pull [OPTIONS] IMAGE[:TAG|@DIGEST]`
7. **podman-push**
- Description: Push an image, manifest list, or image index from local storage to elsewhere.
- Usage: `podman push [OPTIONS] IMAGE[:TAG] [DESTINATION]`
8. **podman-save**
- Description: Save image(s) to an archive.
- Usage: `podman save [OPTIONS] IMAGE [IMAGE...]`
- Flags:
- `-o, --output`: Write to specified file.
### Execution and Interaction:
1. **podman-exec**
- Description: Execute a command in a running container.
- Usage: `podman exec [OPTIONS] CONTAINER COMMAND [ARG...]`
- Flags:
- `-i, --interactive`: Attach with standard input connected.
- `-t, --tty`: Allocate a pseudo-TTY.
2. **podman-logs**
- Description: Display the logs of one or more containers.
- Usage: `podman logs [OPTIONS] CONTAINER [CONTAINER...]`
- Flags:
- `-f, --follow`: Follow log output.
3. **podman-ps**
- Description: Print out information about containers.
- Usage: `podman ps [OPTIONS]`
- Flags:
- `--all`: Show all containers (including stopped).
### Network and Volume Management:
1. **podman-cp**
- Description: Copy files/folders between a container and the local filesystem.
- Usage: `podman cp [OPTIONS] SRC_CONTAINER:SRC_PATH DEST_PATH | DEST_CONTAINER:DEST_PATH`
2. **podman-network**
- Description: Manage Podman networks.
- Usage: `podman network [OPTIONS] COMMAND`
- Subcommands:
- `list`: List networks.
- `inspect`: Display network configuration.
- `create`: Create a new network.
- `delete`: Remove one or more networks.
- ... and more.
3. **podman-volume**
- Description: Simple management tool for volumes.
- Usage: `podman volume [SUBCOMMAND] [OPTIONS]`
- Subcommands:
- `list`: List volumes.
- `create`: Create a new volume.
- `inspect`: Display volume configuration.
- `remove`: Remove one or more volumes.
- ... and more.

View file

@ -0,0 +1,8 @@
---
obj: concept
wiki: https://en.wikipedia.org/wiki/QR_code
---
# QR Code
The quick response, or QR, Code is a two-dimensional version of the Barcode able to convey a wide variety of information almost instantly with the scan of a mobile device.
One can encode [URLs](../internet/URL.md), Contacts (in vCard format), WiFi-Credentials, Locations or other [ASCII](../files/ASCII.md) data.

35
technology/tools/RSS.md Normal file
View file

@ -0,0 +1,35 @@
---
obj: concept
---
# RSS
RSS (RDF Site Summary or Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a standardized, computer-readable format. Subscribing to RSS feeds can allow a user to keep track of many different websites in a single news aggregator, which constantly monitor sites for new content, removing the need for the user to manually check them. News aggregators (or "RSS readers") can be built into a browser, installed on a desktop computer, or installed on a mobile device.
Websites usually use RSS feeds to publish frequently updated information, such as blog entries, news headlines, episodes of audio and video series, or for distributing podcasts. An RSS document (called "feed", "web feed", or "channel") includes full or summarized text, and metadata, like publishing date and author's name. RSS formats are specified using a generic [XML](../files/XML.md) file.
Although RSS formats have evolved from as early as March 1999, it was between 2005 and 2006 when RSS gained widespread use, and the ("Feed-icon.svg") icon was decided upon by several major web browsers. RSS feed data is presented to users using software called a news aggregator and the passing of content is called web syndication. Users subscribe to feeds either by entering a feed's URI into the reader or by clicking on the browser's feed icon. The RSS reader checks the user's feeds regularly for new information and can automatically download it, if that function is enabled.
## Example
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>RSS Title</title>
<description>This is an example of an RSS feed</description>
<link>http://www.example.com/main.html</link>
<copyright>2020 Example.com All rights reserved</copyright>
<lastBuildDate>Mon, 6 September 2010 00:01:00 +0000</lastBuildDate>
<pubDate>Sun, 6 September 2009 16:20:00 +0000</pubDate>
<ttl>1800</ttl>
<item>
<title>Example entry</title>
<description>Here is some text containing an interesting description.</description>
<link>http://www.example.com/blog/post/1</link>
<guid isPermaLink="false">7bd204c6-1655-4c27-aeee-53f933c5395f</guid>
<pubDate>Sun, 6 September 2009 16:20:00 +0000</pubDate>
</item>
</channel>
</rss>
```

115
technology/tools/Regex.md Normal file
View file

@ -0,0 +1,115 @@
---
obj: concept
aliases: ["Regular Expression"]
wiki: https://en.wikipedia.org/wiki/Regular_expression
---
# Regex
A regular expression (shortened as regex or regexp), is a sequence of characters that specifies a match pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
## Anchors
### `^`
Matches the beginning of the string or line.
Example: `^word`
### `$`
Matches the end of the string or line.
Example: `\.txt$`
## Flags
- `i`: Makes the expression case insensitive
- `g`: Ensures that the expression does not stop on the first match
## Group & References
### `()`
Groups an expression.
Example: `(ha)+`
### `\1`
References a grouped expression. `\1` references the first group, `\2` the second and so on.
Example: `(ha)\s\1`
### `(?:)`
Makes a grouping that cannot be referenced.
Example: `(?:ha)+`
## Character Classes
### `[abc]`
Matches any character in the set.
Example: `b[eo]r`
### `[^abc]`
Matches any character not in the set.
Example: `b[^eo]r`
### `[a-z]`
Matches all characters between two characters, including themselves.
Example: `[e-i]`
### `.`
Matches any character except line breaks.
### `\w`
Matches any alphanumeric character. Including the underline.
### `\W`
Matches any non-alphanumeric character.
### `\d`
Matches any numeric character.
### `\D`
Matches any non-numeric character.
### `\s`
Matches any whitespace character.
### `\S`
Matches any non-whitespace character.
## Lookarounds
### `(?=)`
Positive Lookahead.
Example: `\d(?=after)`
### `(?!)`
Negative Lookahead.
Example: `\d(?!after)`
### `(?<=)`
Positive Lookbehind.
Example: `(?<=behind)\d`
### `(?<!)`
Negative Lookbehind.
Example: `(?<!behind)\d`
## Quantifiers And Alternation
### `+`
Expression matches one or more.
Example: `be+r`
### `*`
Expression matches zero or more.
Example: `be*r`
### `{}`
Expression matches within specified ranges (matches this many times):
- Match exactly: `{4}`
- Match minimum: `{4,}`
- Match between: `{4,9}`
Example: `be{1,2}r`
### `?`
Makes the expression optional or lazy.
Example: `colou?r`
### `|`
Works like OR. It waits for one of the expressions it reserved to match.
Example: `(c|r)at`
## Common Regular Expressions
- IPv4-Address: `\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`
- MAC-Address: `(?:[0-9a-fA-F]{2}\:){5}[0-9a-fA-F]{2}`
- Hex Color Codes: `^#?([a-fA-F0-9]{6})$`
- Mail Address: `^([a-zA-Z09._%-]+@[a-zA-Z09.-]+\.[a-zA-Z]{2,6})*$`

31
technology/tools/Tor.md Normal file
View file

@ -0,0 +1,31 @@
---
website: https://torproject.org
obj: application
---
# The Onion Router (TOR)
The Tor Project (The onion routing) is an open source implementation of onion routing that provides free access to an anonymous proxy network. Its primary goal is to enable online anonymity by protecting against traffic analysis attacks.
Users of the Tor network run an onion proxy software on their machines, which presents a SOCKS interface to its clients. This software connects out to Tor, periodically negotiating a virtual circuit through the Tor network. Tor employs cryptography in a layered manner (hence the 'onion' analogy), ensuring forward secrecy between routers.
As an overlay network it is similiar to [i2p](I2P.md).
## Usage
Start/enable `tor.service`. Alternatively, launch it with `sudo -u tor /usr/bin/tor`.
To use a program over Tor, configure it to use `127.0.0.1` or `localhost` as a SOCKS5 proxy, with port `9050` for plain Tor with standard settings.
The proxy supports remote DNS resolution: use `socks5**h**://localhost:9050` for DNS resolution from the exit node (instead of `socks5` for a local DNS resolution).
## Configuration
Tor reads its configurations from the file `/etc/tor/torrc` by default, or if the latter is not found, from `$HOME/.torrc`. The configuration options are explained on the [Tor website](https://torproject.org/docs/tor-manual.html.en). The default configuration should work fine for most Tor users.
## Hidden Services
Hidden Services are web services behind an onion domain.
To generate onion domains [mkp224o](https://git.hydrar.de/utilities/mkp224o) can be used.
To enable a hidden service add this to `torrc`:
```
HiddenServiceDir /var/lib/tor/hidden_service/
HiddenServicePort 80 127.0.0.1:80
```

View file

@ -0,0 +1,14 @@
---
aliases: ["VM"]
obj: concept
wiki: https://en.wikipedia.org/wiki/Virtual_machine
---
# Virtual Machine
In computing, a virtual machine (VM) is the virtualization or [emulation](../emulation/Emulation.md) of a computer system. Virtual machines are based on computer architectures and provide the functionality of a physical computer.
Virtual Machine can be used to run operating systems in an isolated environment. A similiar concept is [Emulation](../emulation/Emulation.md), which allows different hardware to be simulated.
## Virtual Machine Software
- [bhyve](../bsd/bhyve.md)
- [qemu](../linux/qemu.md)
- [Proxmox](../linux/Proxmox.md)

View file

@ -0,0 +1,6 @@
---
obj: concept
---
# WebDAV
WebDAV (Web Distributed Authoring and Versioning) is an extension of [HTTP](../internet/HTTP.md)/1.1 and therefore can be considered to be a protocol. It contains a set of concepts and accompanying extension methods to allow read and write across the [HTTP](../internet/HTTP.md)/1.1 protocol. Instead of using NFS or [SMB](../applications/web/Samba.md), WebDAV offers file transfers via [HTTP](../internet/HTTP.md). A hosting application with WebDAV support is [dufs](../applications/web/dufs.md).