| 1 |
[](https://travis-ci.org/kolypto/j2cli) |
| 2 |
[](.travis.yml) |
| 3 |
|
| 4 |
j2cli - Jinja2 Command-Line Tool |
| 5 |
================================ |
| 6 |
|
| 7 |
`j2cli` is a command-line tool for templating in shell-scripts, |
| 8 |
leveraging the [Jinja2](http://jinja.pocoo.org/docs/) library. |
| 9 |
|
| 10 |
Features: |
| 11 |
|
| 12 |
* Jinja2 templating |
| 13 |
* INI, YAML, JSON data sources supported |
| 14 |
* Allows the use of environment variables in templates! Hello [Docker](http://www.docker.com/) :) |
| 15 |
|
| 16 |
Inspired by [mattrobenolt/jinja2-cli](https://github.com/mattrobenolt/jinja2-cli) |
| 17 |
|
| 18 |
## Installation |
| 19 |
|
| 20 |
``` |
| 21 |
pip install j2cli |
| 22 |
``` |
| 23 |
|
| 24 |
To enable the YAML support with [pyyaml](http://pyyaml.org/): |
| 25 |
|
| 26 |
``` |
| 27 |
pip install j2cli[yaml] |
| 28 |
``` |
| 29 |
|
| 30 |
## Tutorial |
| 31 |
|
| 32 |
Suppose, you want to have an nginx configuration file template, `nginx.j2`: |
| 33 |
|
| 34 |
```jinja2 |
| 35 |
server { |
| 36 |
listen 80; |
| 37 |
server_name {{ nginx.hostname }}; |
| 38 |
|
| 39 |
root {{ nginx.webroot }}; |
| 40 |
index index.htm; |
| 41 |
} |
| 42 |
``` |
| 43 |
|
| 44 |
And you have a JSON file with the data, `nginx.json`: |
| 45 |
|
| 46 |
```json |
| 47 |
{ |
| 48 |
"nginx":{ |
| 49 |
"hostname": "localhost", |
| 50 |
"webroot": "/var/www/project" |
| 51 |
} |
| 52 |
} |
| 53 |
``` |
| 54 |
|
| 55 |
This is how you render it into a working configuration file: |
| 56 |
|
| 57 |
```bash |
| 58 |
$ j2 -f json nginx.j2 nginx.json > nginx.conf |
| 59 |
``` |
| 60 |
|
| 61 |
The output is saved to `nginx.conf`: |
| 62 |
|
| 63 |
``` |
| 64 |
server { |
| 65 |
listen 80; |
| 66 |
server_name localhost; |
| 67 |
|
| 68 |
root /var/www/project; |
| 69 |
index index.htm; |
| 70 |
} |
| 71 |
``` |
| 72 |
|
| 73 |
Alternatively, you can use the `-o nginx.conf` option. |
| 74 |
|
| 75 |
## Tutorial with environment variables |
| 76 |
|
| 77 |
Suppose, you have a very simple template, `person.xml`: |
| 78 |
|
| 79 |
```jinja2 |
| 80 |
<data><name>{{ name }}</name><age>{{ age }}</age></data> |
| 81 |
``` |
| 82 |
|
| 83 |
What is the easiest way to use j2 here? |
| 84 |
Use environment variables in your bash script: |
| 85 |
|
| 86 |
```bash |
| 87 |
$ export name=Andrew |
| 88 |
$ export age=31 |
| 89 |
$ j2 /tmp/person.xml |
| 90 |
<data><name>Andrew</name><age>31</age></data> |
| 91 |
``` |
| 92 |
|
| 93 |
## Using environment variables |
| 94 |
|
| 95 |
Even when you use yaml or json as the data source, you can always access environment variables |
| 96 |
using the `env()` function: |
| 97 |
|
| 98 |
```jinja2 |
| 99 |
Username: {{ login }} |
| 100 |
Password: {{ env("APP_PASSWORD") }} |
| 101 |
``` |
| 102 |
|
| 103 |
|
| 104 |
## Usage |
| 105 |
|
| 106 |
Compile a template using INI-file data source: |
| 107 |
|
| 108 |
$ j2 config.j2 data.ini |
| 109 |
|
| 110 |
Compile using JSON data source: |
| 111 |
|
| 112 |
$ j2 config.j2 data.json |
| 113 |
|
| 114 |
Compile using YAML data source (requires PyYAML): |
| 115 |
|
| 116 |
$ j2 config.j2 data.yaml |
| 117 |
|
| 118 |
Compile using JSON data on stdin: |
| 119 |
|
| 120 |
$ curl http://example.com/service.json | j2 --format=json config.j2 |
| 121 |
|
| 122 |
Compile using environment variables (hello Docker!): |
| 123 |
|
| 124 |
$ j2 config.j2 |
| 125 |
|
| 126 |
Or even read environment variables from a file: |
| 127 |
|
| 128 |
$ j2 --format=env config.j2 data.env |
| 129 |
|
| 130 |
Or pipe it: (note that you'll have to use the "-" in this particular case): |
| 131 |
|
| 132 |
$ j2 --format=env config.j2 - < data.env |
| 133 |
|
| 134 |
|
| 135 |
# Reference |
| 136 |
`j2` accepts the following arguments: |
| 137 |
|
| 138 |
* `template`: Jinja2 template file to render |
| 139 |
* `data`: (optional) path to the data used for rendering. |
| 140 |
The default is `-`: use stdin. Specify it explicitly when using env! |
| 141 |
|
| 142 |
Options: |
| 143 |
|
| 144 |
* `--format, -f`: format for the data file. The default is `?`: guess from file extension. |
| 145 |
* `--import-env VAR, -e EVAR`: import all environment variables into the template as `VAR`. |
| 146 |
To import environment variables into the global scope, give it an empty string: `--import-env=`. |
| 147 |
(This will overwrite any existing variables!) |
| 148 |
* `-o outfile`: Write rendered template to a file |
| 149 |
* `--undefined`: Allow undefined variables to be used in templates (no error will be raised) |
| 150 |
|
| 151 |
* `--filters filters.py`: Load custom Jinja2 filters and tests from a Python file. |
| 152 |
Will load all top-level functions and register them as filters. |
| 153 |
This option can be used multiple times to import several files. |
| 154 |
* `--tests tests.py`: Load custom Jinja2 filters and tests from a Python file. |
| 155 |
* `--customize custom.py`: A Python file that implements hooks to fine-tune the j2cli behavior. |
| 156 |
This is fairly advanced stuff, use it only if you really need to customize the way Jinja2 is initialized. |
| 157 |
See [Customization](#customization) for more info. |
| 158 |
|
| 159 |
There is some special behavior with environment variables: |
| 160 |
|
| 161 |
* When `data` is not provided (data is `-`), `--format` defaults to `env` and thus reads environment variables |
| 162 |
* When `--format=env`, it can read a special "environment variables" file made like this: `env > /tmp/file.env` |
| 163 |
|
| 164 |
## Formats |
| 165 |
|
| 166 |
|
| 167 |
### env |
| 168 |
Data input from environment variables. |
| 169 |
|
| 170 |
Render directly from the current environment variable values: |
| 171 |
|
| 172 |
$ j2 config.j2 |
| 173 |
|
| 174 |
Or alternatively, read the values from a dotenv file: |
| 175 |
|
| 176 |
``` |
| 177 |
NGINX_HOSTNAME=localhost |
| 178 |
NGINX_WEBROOT=/var/www/project |
| 179 |
NGINX_LOGS=/var/log/nginx/ |
| 180 |
``` |
| 181 |
|
| 182 |
And render with: |
| 183 |
|
| 184 |
$ j2 config.j2 data.env |
| 185 |
$ env | j2 --format=env config.j2 |
| 186 |
|
| 187 |
If you're going to pipe a dotenv file into `j2`, you'll need to use "-" as the second argument to explicitly: |
| 188 |
|
| 189 |
$ j2 config.j2 - < data.env |
| 190 |
|
| 191 |
### ini |
| 192 |
INI data input format. |
| 193 |
|
| 194 |
data.ini: |
| 195 |
|
| 196 |
``` |
| 197 |
[nginx] |
| 198 |
hostname=localhost |
| 199 |
webroot=/var/www/project |
| 200 |
logs=/var/log/nginx/ |
| 201 |
``` |
| 202 |
|
| 203 |
Usage: |
| 204 |
|
| 205 |
$ j2 config.j2 data.ini |
| 206 |
$ cat data.ini | j2 --format=ini config.j2 |
| 207 |
|
| 208 |
### json |
| 209 |
JSON data input format |
| 210 |
|
| 211 |
data.json: |
| 212 |
|
| 213 |
``` |
| 214 |
{ |
| 215 |
"nginx":{ |
| 216 |
"hostname": "localhost", |
| 217 |
"webroot": "/var/www/project", |
| 218 |
"logs": "/var/log/nginx/" |
| 219 |
} |
| 220 |
} |
| 221 |
``` |
| 222 |
|
| 223 |
Usage: |
| 224 |
|
| 225 |
$ j2 config.j2 data.json |
| 226 |
$ cat data.json | j2 --format=ini config.j2 |
| 227 |
|
| 228 |
### yaml |
| 229 |
YAML data input format. |
| 230 |
|
| 231 |
data.yaml: |
| 232 |
|
| 233 |
``` |
| 234 |
nginx: |
| 235 |
hostname: localhost |
| 236 |
webroot: /var/www/project |
| 237 |
logs: /var/log/nginx |
| 238 |
``` |
| 239 |
|
| 240 |
Usage: |
| 241 |
|
| 242 |
$ j2 config.j2 data.yml |
| 243 |
$ cat data.yml | j2 --format=yaml config.j2 |
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
Extras |
| 249 |
====== |
| 250 |
|
| 251 |
## Filters |
| 252 |
|
| 253 |
|
| 254 |
### `docker_link(value, format='{addr}:{port}')` |
| 255 |
Given a Docker Link environment variable value, format it into something else. |
| 256 |
|
| 257 |
This first parses a Docker Link value like this: |
| 258 |
|
| 259 |
DB_PORT=tcp://172.17.0.5:5432 |
| 260 |
|
| 261 |
Into a dict: |
| 262 |
|
| 263 |
```python |
| 264 |
{ |
| 265 |
'proto': 'tcp', |
| 266 |
'addr': '172.17.0.5', |
| 267 |
'port': '5432' |
| 268 |
} |
| 269 |
``` |
| 270 |
|
| 271 |
And then uses `format` to format it, where the default format is '{addr}:{port}'. |
| 272 |
|
| 273 |
More info here: [Docker Links](https://docs.docker.com/userguide/dockerlinks/) |
| 274 |
|
| 275 |
### `env(varname, default=None)` |
| 276 |
Use an environment variable's value inside your template. |
| 277 |
|
| 278 |
This filter is available even when your data source is something other that the environment. |
| 279 |
|
| 280 |
Example: |
| 281 |
|
| 282 |
```jinja2 |
| 283 |
User: {{ user_login }} |
| 284 |
Pass: {{ "USER_PASSWORD"|env }} |
| 285 |
``` |
| 286 |
|
| 287 |
You can provide the default value: |
| 288 |
|
| 289 |
```jinja2 |
| 290 |
Pass: {{ "USER_PASSWORD"|env("-none-") }} |
| 291 |
``` |
| 292 |
|
| 293 |
For your convenience, it's also available as a function: |
| 294 |
|
| 295 |
```jinja2 |
| 296 |
User: {{ user_login }} |
| 297 |
Pass: {{ env("USER_PASSWORD") }} |
| 298 |
``` |
| 299 |
|
| 300 |
Notice that there must be quotes around the environment variable name |
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
Customization |
| 306 |
============= |
| 307 |
|
| 308 |
j2cli now allows you to customize the way the application is initialized: |
| 309 |
|
| 310 |
* Pass additional keywords to Jinja2 environment |
| 311 |
* Modify the context before it's used for rendering |
| 312 |
* Register custom filters and tests |
| 313 |
|
| 314 |
This is done through *hooks* that you implement in a customization file in Python language. |
| 315 |
Just plain functions at the module level. |
| 316 |
|
| 317 |
The following hooks are available: |
| 318 |
|
| 319 |
* `j2_environment_params() -> dict`: returns a `dict` of additional parameters for |
| 320 |
[Jinja2 Environment](http://jinja.pocoo.org/docs/2.10/api/#jinja2.Environment). |
| 321 |
* `j2_environment(env: Environment) -> Environment`: lets you customize the `Environment` object. |
| 322 |
* `alter_context(context: dict) -> dict`: lets you modify the context variables that are going to be |
| 323 |
used for template rendering. You can do all sorts of pre-processing here. |
| 324 |
* `extra_filters() -> dict`: returns a `dict` with extra filters for Jinja2 |
| 325 |
* `extra_tests() -> dict`: returns a `dict` with extra tests for Jinja2 |
| 326 |
|
| 327 |
All of them are optional. |
| 328 |
|
| 329 |
The example customization.py file for your reference: |
| 330 |
|
| 331 |
```python |
| 332 |
# |
| 333 |
# Example customize.py file for j2cli |
| 334 |
# Contains potional hooks that modify the way j2cli is initialized |
| 335 |
|
| 336 |
|
| 337 |
def j2_environment_params(): |
| 338 |
""" Extra parameters for the Jinja2 Environment """ |
| 339 |
# Jinja2 Environment configuration |
| 340 |
# http://jinja.pocoo.org/docs/2.10/api/#jinja2.Environment |
| 341 |
return dict( |
| 342 |
# Just some examples |
| 343 |
|
| 344 |
# Change block start/end strings |
| 345 |
block_start_string='<%', |
| 346 |
block_end_string='%>', |
| 347 |
# Change variable strings |
| 348 |
variable_start_string='<<', |
| 349 |
variable_end_string='>>', |
| 350 |
# Remove whitespace around blocks |
| 351 |
trim_blocks=True, |
| 352 |
lstrip_blocks=True, |
| 353 |
# Enable line statements: |
| 354 |
# http://jinja.pocoo.org/docs/2.10/templates/#line-statements |
| 355 |
line_statement_prefix='#', |
| 356 |
# Keep \n at the end of a file |
| 357 |
keep_trailing_newline=True, |
| 358 |
# Enable custom extensions |
| 359 |
# http://jinja.pocoo.org/docs/2.10/extensions/#jinja-extensions |
| 360 |
extensions=('jinja2.ext.i18n',), |
| 361 |
) |
| 362 |
|
| 363 |
|
| 364 |
def j2_environment(env): |
| 365 |
""" Modify Jinja2 environment |
| 366 |
|
| 367 |
:param env: jinja2.environment.Environment |
| 368 |
:rtype: jinja2.environment.Environment |
| 369 |
""" |
| 370 |
env.globals.update( |
| 371 |
my_function=lambda v: 'my function says "{}"'.format(v) |
| 372 |
) |
| 373 |
return env |
| 374 |
|
| 375 |
|
| 376 |
def alter_context(context): |
| 377 |
""" Modify the context and return it """ |
| 378 |
# An extra variable |
| 379 |
context['ADD'] = '127' |
| 380 |
return context |
| 381 |
|
| 382 |
|
| 383 |
def extra_filters(): |
| 384 |
""" Declare some custom filters. |
| 385 |
|
| 386 |
Returns: dict(name = function) |
| 387 |
""" |
| 388 |
return dict( |
| 389 |
# Example: {{ var | parentheses }} |
| 390 |
parentheses=lambda t: '(' + t + ')', |
| 391 |
) |
| 392 |
|
| 393 |
|
| 394 |
def extra_tests(): |
| 395 |
""" Declare some custom tests |
| 396 |
|
| 397 |
Returns: dict(name = function) |
| 398 |
""" |
| 399 |
return dict( |
| 400 |
# Example: {% if a|int is custom_odd %}odd{% endif %} |
| 401 |
custom_odd=lambda n: True if (n % 2) else False |
| 402 |
) |
| 403 |
|
| 404 |
# |
| 405 |
|
| 406 |
``` |
| 407 |
|