Merge lp:~harlowja/cloud-init/changeable-templates into lp:~cloud-init-dev/cloud-init/trunk

Proposed by Joshua Harlow
Status: Merged
Merged at revision: 981
Proposed branch: lp:~harlowja/cloud-init/changeable-templates
Merge into: lp:~cloud-init-dev/cloud-init/trunk
Diff against target: 655 lines (+372/-159)
10 files modified
cloudinit/templater.py (+111/-4)
requirements.txt (+1/-0)
templates/chef_client.rb.tmpl (+15/-15)
templates/hosts.debian.tmpl (+11/-10)
templates/hosts.redhat.tmpl (+9/-8)
templates/hosts.suse.tmpl (+8/-6)
templates/resolv.conf.tmpl (+25/-34)
templates/sources.list.debian.tmpl (+29/-25)
templates/sources.list.ubuntu.tmpl (+57/-57)
tests/unittests/test_templating.py (+106/-0)
To merge this branch: bzr merge lp:~harlowja/cloud-init/changeable-templates
Reviewer Review Type Date Requested Status
cloud-init Commiters Pending
Review via email: mp+208994@code.launchpad.net

Description of the change

Allow the usage of jinja templates

Jinja is a python 2.4->3.x compatible
templating engine, allow its optional
usage (until we can depreciate cheetah)
by allowing for specifying a template
file header that can define which template
engine to use.

For now support cheetah (the default) and
if specified support jinja as well. If neither
are available use a crappy renderer that can
expand basic bash-like variables (and that's
all it can do).

To post a comment you must log in.
964. By Joshua Harlow

Switch to jinja & adjust tpls

965. By Joshua Harlow

Add some basic template tests

Revision history for this message
Scott Moser (smoser) wrote :

Josh,
  Thank you.
  This looks great.
  The only thing I'd like to suggest is that we dont stack trace on failed import of jinja or cheetah, but rather fail to render loudly (possibly even with stack trace) if that engine is necessary.

  Ie, your code makes it so we only need cheetah if there are templates without the header and we fall back to that engine. No reason to stack trace then, as the default case we wont need them.

  Also, bonus points for a "no cheetah dependency cheetah rendering engine". Ie, if 'mport cheetah' fails, then we can log that as a warning, and try a builtin crappy renderer that does:
    for k, v in params:
       content.replace('$' + k, v)

966. By Joshua Harlow

Add basic renderer support and more robust import handling

967. By Joshua Harlow

Log the renderer type when rendering files

968. By Joshua Harlow

Add non braces matching and a few more tests

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'cloudinit/templater.py'
--- cloudinit/templater.py 2012-07-09 20:41:45 +0000
+++ cloudinit/templater.py 2014-07-18 17:52:57 +0000
@@ -20,13 +20,119 @@
20# You should have received a copy of the GNU General Public License20# You should have received a copy of the GNU General Public License
21# along with this program. If not, see <http://www.gnu.org/licenses/>.21# along with this program. If not, see <http://www.gnu.org/licenses/>.
2222
23from Cheetah.Template import Template23import collections
2424import re
25
26try:
27 from Cheetah.Template import Template as CTemplate
28 CHEETAH_AVAILABLE = True
29except (ImportError, AttributeError):
30 CHEETAH_AVAILABLE = False
31
32try:
33 import jinja2
34 from jinja2 import Template as JTemplate
35 JINJA_AVAILABLE = True
36except (ImportError, AttributeError):
37 JINJA_AVAILABLE = False
38
39from cloudinit import log as logging
40from cloudinit import type_utils as tu
25from cloudinit import util41from cloudinit import util
2642
43LOG = logging.getLogger(__name__)
44TYPE_MATCHER = re.compile(r"##\s*template:(.*)", re.I)
45BASIC_MATCHER = re.compile(r'\$\{([A-Za-z0-9_.]+)\}|\$([A-Za-z0-9_.]+)')
46
47
48def basic_render(content, params):
49 """This does simple replacement of bash variable like templates.
50
51 It identifies patterns like ${a} or $a and can also identify patterns like
52 ${a.b} or $a.b which will look for a key 'b' in the dictionary rooted
53 by key 'a'.
54 """
55
56 def replacer(match):
57 # Only 1 of the 2 groups will actually have a valid entry.
58 name = match.group(1)
59 if name is None:
60 name = match.group(2)
61 if name is None:
62 raise RuntimeError("Match encountered but no valid group present")
63 path = collections.deque(name.split("."))
64 selected_params = params
65 while len(path) > 1:
66 key = path.popleft()
67 if not isinstance(selected_params, dict):
68 raise TypeError("Can not traverse into"
69 " non-dictionary '%s' of type %s while"
70 " looking for subkey '%s'"
71 % (selected_params,
72 tu.obj_name(selected_params),
73 key))
74 selected_params = selected_params[key]
75 key = path.popleft()
76 if not isinstance(selected_params, dict):
77 raise TypeError("Can not extract key '%s' from non-dictionary"
78 " '%s' of type %s"
79 % (key, selected_params,
80 tu.obj_name(selected_params)))
81 return str(selected_params[key])
82
83 return BASIC_MATCHER.sub(replacer, content)
84
85
86def detect_template(text):
87
88 def cheetah_render(content, params):
89 return CTemplate(content, searchList=[params]).respond()
90
91 def jinja_render(content, params):
92 return JTemplate(content,
93 undefined=jinja2.StrictUndefined,
94 trim_blocks=True).render(**params)
95
96 if text.find("\n") != -1:
97 ident, rest = text.split("\n", 1)
98 else:
99 ident = text
100 rest = ''
101 type_match = TYPE_MATCHER.match(ident)
102 if not type_match:
103 if not CHEETAH_AVAILABLE:
104 LOG.warn("Cheetah not available as the default renderer for"
105 " unknown template, reverting to the basic renderer.")
106 return ('basic', basic_render, text)
107 else:
108 return ('cheetah', cheetah_render, text)
109 else:
110 template_type = type_match.group(1).lower().strip()
111 if template_type not in ('jinja', 'cheetah', 'basic'):
112 raise ValueError("Unknown template rendering type '%s' requested"
113 % template_type)
114 if template_type == 'jinja' and not JINJA_AVAILABLE:
115 LOG.warn("Jinja not available as the selected renderer for"
116 " desired template, reverting to the basic renderer.")
117 return ('basic', basic_render, rest)
118 elif template_type == 'jinja' and JINJA_AVAILABLE:
119 return ('jinja', jinja_render, rest)
120 if template_type == 'cheetah' and not CHEETAH_AVAILABLE:
121 LOG.warn("Cheetah not available as the selected renderer for"
122 " desired template, reverting to the basic renderer.")
123 return ('basic', basic_render, rest)
124 elif template_type == 'cheetah' and CHEETAH_AVAILABLE:
125 return ('cheetah', cheetah_render, rest)
126 # Only thing left over is the basic renderer (it is always available).
127 return ('basic', basic_render, rest)
128
27129
28def render_from_file(fn, params):130def render_from_file(fn, params):
29 return render_string(util.load_file(fn), params)131 if not params:
132 params = {}
133 template_type, renderer, content = detect_template(util.load_file(fn))
134 LOG.debug("Rendering content of '%s' using renderer %s", fn, template_type)
135 return renderer(content, params)
30136
31137
32def render_to_file(fn, outfn, params, mode=0644):138def render_to_file(fn, outfn, params, mode=0644):
@@ -37,4 +143,5 @@
37def render_string(content, params):143def render_string(content, params):
38 if not params:144 if not params:
39 params = {}145 params = {}
40 return Template(content, searchList=[params]).respond()146 template_type, renderer, content = detect_template(content)
147 return renderer(content, params)
41148
=== modified file 'requirements.txt'
--- requirements.txt 2014-02-12 10:14:49 +0000
+++ requirements.txt 2014-07-18 17:52:57 +0000
@@ -2,6 +2,7 @@
22
3# Used for untemplating any files or strings with parameters.3# Used for untemplating any files or strings with parameters.
4cheetah4cheetah
5jinja2
56
6# This is used for any pretty printing of tabular data.7# This is used for any pretty printing of tabular data.
7PrettyTable8PrettyTable
89
=== modified file 'templates/chef_client.rb.tmpl'
--- templates/chef_client.rb.tmpl 2012-07-09 20:45:26 +0000
+++ templates/chef_client.rb.tmpl 2014-07-18 17:52:57 +0000
@@ -1,25 +1,25 @@
1#*1## template:jinja
2 This file is only utilized if the module 'cc_chef' is enabled in 2{#
3 cloud-config. Specifically, in order to enable it3This file is only utilized if the module 'cc_chef' is enabled in
4 you need to add the following to config:4cloud-config. Specifically, in order to enable it
5 chef:5you need to add the following to config:
6 validation_key: XYZ6 chef:
7 validation_cert: XYZ7 validation_key: XYZ
8 validation_name: XYZ8 validation_cert: XYZ
9 server_url: XYZ9 validation_name: XYZ
10*#10 server_url: XYZ
11-#}
11log_level :info12log_level :info
12log_location "/var/log/chef/client.log"13log_location "/var/log/chef/client.log"
13ssl_verify_mode :verify_none14ssl_verify_mode :verify_none
14validation_client_name "$validation_name"15validation_client_name "{{validation_name}}"
15validation_key "/etc/chef/validation.pem"16validation_key "/etc/chef/validation.pem"
16client_key "/etc/chef/client.pem"17client_key "/etc/chef/client.pem"
17chef_server_url "$server_url"18chef_server_url "{{server_url}}"
18environment "$environment"19environment "{{environment}}"
19node_name "$node_name"20node_name "{{node_name}}"
20json_attribs "/etc/chef/firstboot.json"21json_attribs "/etc/chef/firstboot.json"
21file_cache_path "/var/cache/chef"22file_cache_path "/var/cache/chef"
22file_backup_path "/var/backups/chef"23file_backup_path "/var/backups/chef"
23pid_file "/var/run/chef/client.pid"24pid_file "/var/run/chef/client.pid"
24Chef::Log::Formatter.show_time = true25Chef::Log::Formatter.show_time = true
25
2626
=== modified file 'templates/hosts.debian.tmpl'
--- templates/hosts.debian.tmpl 2013-01-15 21:34:51 +0000
+++ templates/hosts.debian.tmpl 2014-07-18 17:52:57 +0000
@@ -1,19 +1,19 @@
1## This file (/etc/cloud/templates/hosts.tmpl) is only utilized1## template:jinja
2## if enabled in cloud-config. Specifically, in order to enable it2{#
3## you need to add the following to config:3This file (/etc/cloud/templates/hosts.tmpl) is only utilized
4## manage_etc_hosts: True4if enabled in cloud-config. Specifically, in order to enable it
5##5you need to add the following to config:
6## Note, double-hash commented lines will not appear in /etc/hosts6 manage_etc_hosts: True
7# 7-#}
8# Your system has configured 'manage_etc_hosts' as True.8# Your system has configured 'manage_etc_hosts' as True.
9# As a result, if you wish for changes to this file to persist9# As a result, if you wish for changes to this file to persist
10# then you will need to either10# then you will need to either
11# a.) make changes to the master file in /etc/cloud/templates/hosts.tmpl11# a.) make changes to the master file in /etc/cloud/templates/hosts.tmpl
12# b.) change or remove the value of 'manage_etc_hosts' in12# b.) change or remove the value of 'manage_etc_hosts' in
13# /etc/cloud/cloud.cfg or cloud-config from user-data13# /etc/cloud/cloud.cfg or cloud-config from user-data
14# 14#
15## The value '$hostname' will be replaced with the local-hostname15{# The value '{{hostname}}' will be replaced with the local-hostname -#}
16127.0.1.1 $fqdn $hostname16127.0.1.1 {{fqdn}} {{hostname}}
17127.0.0.1 localhost17127.0.0.1 localhost
1818
19# The following lines are desirable for IPv6 capable hosts19# The following lines are desirable for IPv6 capable hosts
@@ -23,3 +23,4 @@
23ff02::1 ip6-allnodes23ff02::1 ip6-allnodes
24ff02::2 ip6-allrouters24ff02::2 ip6-allrouters
25ff02::3 ip6-allhosts25ff02::3 ip6-allhosts
26
2627
=== modified file 'templates/hosts.redhat.tmpl'
--- templates/hosts.redhat.tmpl 2012-07-09 20:41:45 +0000
+++ templates/hosts.redhat.tmpl 2014-07-18 17:52:57 +0000
@@ -1,9 +1,10 @@
1#*1## template:jinja
2 This file /etc/cloud/templates/hosts.redhat.tmpl is only utilized2{#
3 if enabled in cloud-config. Specifically, in order to enable it3This file /etc/cloud/templates/hosts.redhat.tmpl is only utilized
4 you need to add the following to config:4if enabled in cloud-config. Specifically, in order to enable it
5 manage_etc_hosts: True5you need to add the following to config:
6*#6 manage_etc_hosts: True
7-#}
7# Your system has configured 'manage_etc_hosts' as True.8# Your system has configured 'manage_etc_hosts' as True.
8# As a result, if you wish for changes to this file to persist9# As a result, if you wish for changes to this file to persist
9# then you will need to either10# then you will need to either
@@ -12,12 +13,12 @@
12# /etc/cloud/cloud.cfg or cloud-config from user-data13# /etc/cloud/cloud.cfg or cloud-config from user-data
13# 14#
14# The following lines are desirable for IPv4 capable hosts15# The following lines are desirable for IPv4 capable hosts
15127.0.0.1 ${fqdn} ${hostname} 16127.0.0.1 {{fqdn}} {{hostname}}
16127.0.0.1 localhost.localdomain localhost17127.0.0.1 localhost.localdomain localhost
17127.0.0.1 localhost4.localdomain4 localhost418127.0.0.1 localhost4.localdomain4 localhost4
1819
19# The following lines are desirable for IPv6 capable hosts20# The following lines are desirable for IPv6 capable hosts
20::1 ${fqdn} ${hostname}21::1 {{fqdn}} {{hostname}}
21::1 localhost.localdomain localhost22::1 localhost.localdomain localhost
22::1 localhost6.localdomain6 localhost623::1 localhost6.localdomain6 localhost6
2324
2425
=== modified file 'templates/hosts.suse.tmpl'
--- templates/hosts.suse.tmpl 2013-06-25 06:56:57 +0000
+++ templates/hosts.suse.tmpl 2014-07-18 17:52:57 +0000
@@ -1,9 +1,10 @@
1#*1## template:jinja
2 This file /etc/cloud/templates/hosts.suse.tmpl is only utilized2{#
3 if enabled in cloud-config. Specifically, in order to enable it3This file /etc/cloud/templates/hosts.suse.tmpl is only utilized
4 you need to add the following to config:4if enabled in cloud-config. Specifically, in order to enable it
5 manage_etc_hosts: True5you need to add the following to config:
6*#6 manage_etc_hosts: True
7-#}
7# Your system has configured 'manage_etc_hosts' as True.8# Your system has configured 'manage_etc_hosts' as True.
8# As a result, if you wish for changes to this file to persist9# As a result, if you wish for changes to this file to persist
9# then you will need to either10# then you will need to either
@@ -22,3 +23,4 @@
22ff02::1 ipv6-allnodes23ff02::1 ipv6-allnodes
23ff02::2 ipv6-allrouters24ff02::2 ipv6-allrouters
24ff02::3 ipv6-allhosts25ff02::3 ipv6-allhosts
26
2527
=== modified file 'templates/resolv.conf.tmpl'
--- templates/resolv.conf.tmpl 2013-01-17 05:09:49 +0000
+++ templates/resolv.conf.tmpl 2014-07-18 17:52:57 +0000
@@ -1,39 +1,30 @@
1#1## template:jinja
2# Your system has been configured with 'manage-resolv-conf' set to true.2# Your system has been configured with 'manage-resolv-conf' set to true.
3# As a result, cloud-init has written this file with configuration data3# As a result, cloud-init has written this file with configuration data
4# that it has been provided. Cloud-init, by default, will write this file4# that it has been provided. Cloud-init, by default, will write this file
5# a single time (PER_ONCE).5# a single time (PER_ONCE).
6#6#
77{% if nameservers is defined %}
8#if $varExists('nameservers')8{% for server in nameservers %}
9#for $server in $nameservers9nameserver {{server}}
10nameserver $server10{% endfor %}
11#end for11
12#end if12{% endif -%}
13#if $varExists('searchdomains')13{% if searchdomains is defined %}
14search #slurp14search {% for search in searchdomains %}{{search}} {% endfor %}
15#for $search in $searchdomains15
16$search #slurp16{% endif %}
17#end for17{% if domain is defined %}
1818domain {{domain}}
19#end if19{% endif %}
20#if $varExists('domain')20{% if sortlist is defined %}
21domain $domain21
22#end if22sortlist {% for sort in sortlist %}{{sort}} {% endfor %}
23#if $varExists('sortlist')23{% endif %}
24sortlist #slurp24{% if options is defined or flags is defined %}
25#for $sort in $sortlist25
26$sort #slurp26options {% for flag in flags %}{{flag}} {% endfor %}
27#end for27{% for key, value in options.iteritems() -%}
2828 {{key}}:{{value}}
29#end if29{% endfor %}
30#if $varExists('options') or $varExists('flags')30{% endif %}
31options #slurp
32#for $flag in $flags
33$flag #slurp
34#end for
35#for $key, $value in $options.items()
36$key:$value #slurp
37#end for
38
39#end if
4031
=== modified file 'templates/sources.list.debian.tmpl'
--- templates/sources.list.debian.tmpl 2013-02-21 15:29:06 +0000
+++ templates/sources.list.debian.tmpl 2014-07-18 17:52:57 +0000
@@ -1,28 +1,32 @@
1\## Note, this file is written by cloud-init on first boot of an instance1## template:jinja
2\## modifications made here will not survive a re-bundle.2## Note, this file is written by cloud-init on first boot of an instance
3\## if you wish to make changes you can:3## modifications made here will not survive a re-bundle.
4\## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg4## if you wish to make changes you can:
5\## or do the same in user-data5## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg
6\## b.) add sources in /etc/apt/sources.list.d6## or do the same in user-data
7\## c.) make changes to template file /etc/cloud/templates/sources.list.debian.tmpl7## b.) add sources in /etc/apt/sources.list.d
8\###8## c.) make changes to template file /etc/cloud/templates/sources.list.debian.tmpl
9###
910
10# See http://www.debian.org/releases/stable/i386/release-notes/ch-upgrading.html11# See http://www.debian.org/releases/stable/i386/release-notes/ch-upgrading.html
11# for how to upgrade to newer versions of the distribution.12# for how to upgrade to newer versions of the distribution.
12deb $mirror $codename main contrib non-free13deb {{mirror}} {{codename}} main contrib non-free
13deb-src $mirror $codename main contrib non-free14deb-src {{mirror}} {{codename}} main contrib non-free
1415
15\## Major bug fix updates produced after the final release of the16## Major bug fix updates produced after the final release of the
16\## distribution.17## distribution.
17deb $security $codename/updates main contrib non-free18deb {{security}} {{codename}}/updates main contrib non-free
18deb-src $security $codename/updates main contrib non-free19deb-src {{security}} {{codename}}/updates main contrib non-free
19deb $mirror $codename-updates main contrib non-free20deb {{mirror}} {{codename}}-updates main contrib non-free
20deb-src $mirror $codename-updates main contrib non-free21deb-src {{mirror}} {{codename}}-updates main contrib non-free
2122
22\## Uncomment the following two lines to add software from the 'backports'23## Uncomment the following two lines to add software from the 'backports'
23\## repository.24## repository.
24\## N.B. software from this repository may not have been tested as25##
25\## extensively as that contained in the main release, although it includes26## N.B. software from this repository may not have been tested as
26\## newer versions of some applications which may provide useful features.27## extensively as that contained in the main release, although it includes
27# deb http://backports.debian.org/debian-backports $codename-backports main contrib non-free28## newer versions of some applications which may provide useful features.
28# deb-src http://backports.debian.org/debian-backports $codename-backports main contrib non-free29{#
30deb http://backports.debian.org/debian-backports {{codename}}-backports main contrib non-free
31deb-src http://backports.debian.org/debian-backports {{codename}}-backports main contrib non-free
32-#}
2933
=== modified file 'templates/sources.list.ubuntu.tmpl'
--- templates/sources.list.ubuntu.tmpl 2013-02-21 15:29:06 +0000
+++ templates/sources.list.ubuntu.tmpl 2014-07-18 17:52:57 +0000
@@ -1,60 +1,60 @@
1\## Note, this file is written by cloud-init on first boot of an instance1## template:jinja
2\## modifications made here will not survive a re-bundle.2## Note, this file is written by cloud-init on first boot of an instance
3\## if you wish to make changes you can:3## modifications made here will not survive a re-bundle.
4\## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg4## if you wish to make changes you can:
5\## or do the same in user-data5## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg
6\## b.) add sources in /etc/apt/sources.list.d6## or do the same in user-data
7\## c.) make changes to template file /etc/cloud/templates/sources.list.tmpl7## b.) add sources in /etc/apt/sources.list.d
8\###8## c.) make changes to template file /etc/cloud/templates/sources.list.tmpl
99
10# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to10# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
11# newer versions of the distribution.11# newer versions of the distribution.
12deb $mirror $codename main12deb {{mirror}} {{codename}} main
13deb-src $mirror $codename main13deb-src {{mirror}} {{codename}} main
1414
15\## Major bug fix updates produced after the final release of the15## Major bug fix updates produced after the final release of the
16\## distribution.16## distribution.
17deb $mirror $codename-updates main17deb {{mirror}} {{codename}}-updates main
18deb-src $mirror $codename-updates main18deb-src {{mirror}} {{codename}}-updates main
1919
20\## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu20## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
21\## team. Also, please note that software in universe WILL NOT receive any21## team. Also, please note that software in universe WILL NOT receive any
22\## review or updates from the Ubuntu security team.22## review or updates from the Ubuntu security team.
23deb $mirror $codename universe23deb {{mirror}} {{codename}} universe
24deb-src $mirror $codename universe24deb-src {{mirror}} {{codename}} universe
25deb $mirror $codename-updates universe25deb {{mirror}} {{codename}}-updates universe
26deb-src $mirror $codename-updates universe26deb-src {{mirror}} {{codename}}-updates universe
2727
28\## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu 28## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
29\## team, and may not be under a free licence. Please satisfy yourself as to29## team, and may not be under a free licence. Please satisfy yourself as to
30\## your rights to use the software. Also, please note that software in 30## your rights to use the software. Also, please note that software in
31\## multiverse WILL NOT receive any review or updates from the Ubuntu31## multiverse WILL NOT receive any review or updates from the Ubuntu
32\## security team.32## security team.
33# deb $mirror $codename multiverse33# deb {{mirror}} {{codename}} multiverse
34# deb-src $mirror $codename multiverse34# deb-src {{mirror}} {{codename}} multiverse
35# deb $mirror $codename-updates multiverse35# deb {{mirror}} {{codename}}-updates multiverse
36# deb-src $mirror $codename-updates multiverse36# deb-src {{mirror}} {{codename}}-updates multiverse
3737
38\## Uncomment the following two lines to add software from the 'backports'38## Uncomment the following two lines to add software from the 'backports'
39\## repository.39## repository.
40\## N.B. software from this repository may not have been tested as40## N.B. software from this repository may not have been tested as
41\## extensively as that contained in the main release, although it includes41## extensively as that contained in the main release, although it includes
42\## newer versions of some applications which may provide useful features.42## newer versions of some applications which may provide useful features.
43\## Also, please note that software in backports WILL NOT receive any review43## Also, please note that software in backports WILL NOT receive any review
44\## or updates from the Ubuntu security team.44## or updates from the Ubuntu security team.
45# deb $mirror $codename-backports main restricted universe multiverse45# deb {{mirror}} {{codename}}-backports main restricted universe multiverse
46# deb-src $mirror $codename-backports main restricted universe multiverse46# deb-src {{mirror}} {{codename}}-backports main restricted universe multiverse
4747
48\## Uncomment the following two lines to add software from Canonical's48## Uncomment the following two lines to add software from Canonical's
49\## 'partner' repository.49## 'partner' repository.
50\## This software is not part of Ubuntu, but is offered by Canonical and the50## This software is not part of Ubuntu, but is offered by Canonical and the
51\## respective vendors as a service to Ubuntu users.51## respective vendors as a service to Ubuntu users.
52# deb http://archive.canonical.com/ubuntu $codename partner52# deb http://archive.canonical.com/ubuntu {{codename}} partner
53# deb-src http://archive.canonical.com/ubuntu $codename partner53# deb-src http://archive.canonical.com/ubuntu {{codename}} partner
5454
55deb $security $codename-security main55deb {{security}} {{codename}}-security main
56deb-src $security $codename-security main56deb-src {{security}} {{codename}}-security main
57deb $security $codename-security universe57deb {{security}} {{codename}}-security universe
58deb-src $security $codename-security universe58deb-src {{security}} {{codename}}-security universe
59# deb $security $codename-security multiverse59# deb {{security}} {{codename}}-security multiverse
60# deb-src $security $codename-security multiverse60# deb-src {{security}} {{codename}}-security multiverse
6161
=== added file 'tests/unittests/test_templating.py'
--- tests/unittests/test_templating.py 1970-01-01 00:00:00 +0000
+++ tests/unittests/test_templating.py 2014-07-18 17:52:57 +0000
@@ -0,0 +1,106 @@
1# vi: ts=4 expandtab
2#
3# Copyright (C) 2014 Yahoo! Inc.
4#
5# Author: Joshua Harlow <harlowja@yahoo-inc.com>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License version 3, as
9# published by the Free Software Foundation.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19from tests.unittests import helpers as test_helpers
20
21from cloudinit import templater
22
23
24class TestTemplates(test_helpers.TestCase):
25 def test_render_basic(self):
26 in_data = """
27${b}
28
29c = d
30"""
31 in_data = in_data.strip()
32 expected_data = """
332
34
35c = d
36"""
37 out_data = templater.basic_render(in_data, {'b': 2})
38 self.assertEqual(expected_data.strip(), out_data)
39
40 def test_detection(self):
41 blob = "## template:cheetah"
42
43 (template_type, renderer, contents) = templater.detect_template(blob)
44 self.assertIn("cheetah", template_type)
45 self.assertEqual("", contents.strip())
46
47 blob = "blahblah $blah"
48 (template_type, renderer, contents) = templater.detect_template(blob)
49 self.assertIn("cheetah", template_type)
50 self.assertEquals(blob, contents)
51
52 blob = '##template:something-new'
53 self.assertRaises(ValueError, templater.detect_template, blob)
54
55 def test_render_cheetah(self):
56 blob = '''## template:cheetah
57$a,$b'''
58 c = templater.render_string(blob, {"a": 1, "b": 2})
59 self.assertEquals("1,2", c)
60
61 def test_render_jinja(self):
62 blob = '''## template:jinja
63{{a}},{{b}}'''
64 c = templater.render_string(blob, {"a": 1, "b": 2})
65 self.assertEquals("1,2", c)
66
67 def test_render_default(self):
68 blob = '''$a,$b'''
69 c = templater.render_string(blob, {"a": 1, "b": 2})
70 self.assertEquals("1,2", c)
71
72 def test_render_basic_deeper(self):
73 hn = 'myfoohost.yahoo.com'
74 expected_data = "h=%s\nc=d\n" % hn
75 in_data = "h=$hostname.canonical_name\nc=d\n"
76 params = {
77 "hostname": {
78 "canonical_name": hn,
79 },
80 }
81 out_data = templater.render_string(in_data, params)
82 self.assertEqual(expected_data, out_data)
83
84 def test_render_basic_no_parens(self):
85 hn = "myfoohost"
86 in_data = "h=$hostname\nc=d\n"
87 expected_data = "h=%s\nc=d\n" % hn
88 out_data = templater.basic_render(in_data, {'hostname': hn})
89 self.assertEqual(expected_data, out_data)
90
91 def test_render_basic_parens(self):
92 hn = "myfoohost"
93 in_data = "h = ${hostname}\nc=d\n"
94 expected_data = "h = %s\nc=d\n" % hn
95 out_data = templater.basic_render(in_data, {'hostname': hn})
96 self.assertEqual(expected_data, out_data)
97
98 def test_render_basic2(self):
99 mirror = "mymirror"
100 codename = "zany"
101 in_data = "deb $mirror $codename-updates main contrib non-free"
102 ex_data = "deb %s %s-updates main contrib non-free" % (mirror, codename)
103
104 out_data = templater.basic_render(in_data,
105 {'mirror': mirror, 'codename': codename})
106 self.assertEqual(ex_data, out_data)