1

My program is in Python and my configuration file is in yaml. I would like to use variables and some math expressions in my yaml file. (eg: $var + $offset) It seems like Ansible supports both, but I am not familiar with Ansible and not sure whether I can only import the part which handles yaml configuration. Any help will be appreciated.

Reference: Ansible - Can I use arithmetic when setting a variable value?


Update:

Ideally, I would like to use playbook feature from Ansible as a library. Something like described here: http://oriolrius.cat/blog/2015/01/21/using-ansible-like-library-programming-in-python/ But I couldn't make it work seems like the instruction is outdated.

Alex
  • 2,915
  • 5
  • 28
  • 38

2 Answers2

6

Ansible supports the use of Jinja templates. You can set your variables in any kind of file and send it remotelly, depending on your needs.

You can refer to variables in YAML using Jinja syntax ( {{ variable }} ), more info here.

You can also use templates, in case you need to perform other operations with said variables.

As the example you sent, you can use jinja math:

vars:
  your_result: "{{ your_var + your_offset }}"
Rebeca Maia
  • 438
  • 4
  • 16
  • Can I use Ansible as a library to get the configurations? – Alex Dec 11 '17 at 19:18
  • Hi Rebeca, I have updated my post. Hope it's clearer now. I just want to use the playbook features (variables and math expression in yaml) from my python program. – Alex Dec 11 '17 at 19:24
  • Alex, there's a python API for ansible, you may want to give it a go: http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html – Rebeca Maia Dec 11 '17 at 19:43
0

Finally I have figured out how to do it. I just need to use jinja2 library instead of trying to use Ansible as a library. (Ansible's playbook feature is just an implementation of Jinja syntax)

Thanks to @Rebeca Maia who inspired me by mentioning Jinja.

Here is a code example - python file:

import os
from jinja2 import Environment, FileSystemLoader
import yaml

DIR_PATH = os.path.dirname(os.path.realpath(__file__))
env = Environment(loader=FileSystemLoader(DIR_PATH))
template = env.get_template("test_config.yaml")
c = template.render(name='John Doe', val=10)
# yaml :)
config_vals = yaml.load(c)
print config_vals

yaml file

email: "python-test-user@hotmail.com"
user: {{name}}
age: {{10+val}}
Alex
  • 2,915
  • 5
  • 28
  • 38