how to pass 2 data bag variables to template chef - templates

I am trying to pass 2 data bags as variables into a template but it end in error message. Do anyone know how do i pass 2 databags to a template?
Recipe
db = data_bag_item('dbconnect', 'connection')
dbkey = data_bag_item('database', 'databasename')
template '/etc/config.cnf' do
source 'config.cnf.erb'
action :create
variables (
:dbcon => db,
:dbk => dbkey
)
end
Template
connection = mysql://<%= #dbcon['dbuser'] %>:<%= #dbcon['dbpasswd'] %>#<%= #dbcon['dbname'] %>/<%= #dbk['dbname'] %>

Okay. I got the answer.
I missed {} brackets in variables.
db = data_bag_item('dbconnect', 'connection')
dbkey = data_bag_item('database', 'databasename')
template '/etc/config.cnf' do
source 'config.cnf.erb'
action :create
variables ({
:dbcon => db,
:dbk => dbkey
})
end

Related

Can't see custom attributes set on a user from their Google_Service_Directory_User object

When a custom attribute is set on a user from googles admin page I am unable to see it in their Google_Service_Directory_User object the client has this scope and is able to see the users data but no attributes are shown.
$client->setScopes(
[
Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY,
Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY,
]
);
I would have expected it to be in the customSchemas but that is null for all the users
When requesting user's informations, you need to set the projection parameter to FULL when using the method users.get (projection parameter is also avaible with method users.list). Default settings to not return custom schemas. You can have more informations here (Google documentation).
You seem to be using PHP (I've never coded in PHP so I may be wrong), so the request should look like this:
$optParams = array(
'userKey' => 'my_customer#example.com',
'projection' => 'full', // or maybe 'FULL' ?
);
$results = $service->users->get($optParams);
If you only want the return some of the schemas, then use :
$optParams = array(
'userKey' => 'my_customer#example.com',
'projection' => 'custom', // or maybe 'CUSTOM' ?,
'customFieldMask' => 'A comma-separated list of schema names'
);
$results = $service->users->get($optParams);

It is possible to somehow use forward_missing_to to fetch/set hash values?

I am building client for Asterisk Manager (AMI), which sending back "events" (strings in key-value format). Depending on event type the keys are different. Some known would be defined similar as a property, but I also want to access everything else similar way (I need only getter).
Below is example and I am confused about forward_missing_to, to fetch hash value (i.e. e.foo => e.data["foo"] and e.foo? => e.data["foo"]?
class Event
#data = Hash(String,String).new
def initialize(data : Hash(String, String))
#data.merge! data
end
# known field (event), here I could apply various validations etc.
def event=(#name : String)
#data["name"] = #name
end
def event : String
#data["name"].not_nil!
end
# Confusing about this:
forward_missing_to #data
end
Example of usage:
e = Event.new({"event" => "Test", "foo" => "bar"})
p e.event # => "Test" (only this works)
p e.foo # => expecting to get "bar"
p e.unknown # => should throw Unhandled exception: Missing hash key: "unknown" (KeyError)
p e.unknown? # => nil
forward_missing_to just means this:
e = Event.new({"event" => "Test", "foo" => "bar"})
# Same as invoking `foo` on the #data instance variable
# because you said forward_missing_to #data
e.foo
It doesn't mean invoking ["foo"] on #data.
You can do it like this:
macro method_missing(call)
{% if call.args.empty? && !call.named_args %}
#data[{{call.name.stringify}}]
{% else %}
{% raise "undefined method '#{call.name}' for #{#type}" %}
{% end %}
end
However, I wouldn't advise using method_missing, mainly because it might be eventually removed from the language (together with forward_missing_to).

How to include a subtemplate in a puppet template using future parser

During our upgrade up from Puppet 3.5.7 and after piecing together information from:
How to include a subtemplate in a Puppet template
I could reference a subtemplate with some variable in the filename like so:
<%= scope.function_template([File.dirname(__FILE__) + "/" + "subtemplate_" + #oscar_package + ".properties.erb"]) %>
After enabling the future parser I get the following error:
Error: Could not retrieve catalog from remote server: Error 400 on
SERVER: Evaluation Error: Error while evaluating a Function Call,
Failed to parse template
oscar_mysql_tomcat/context/oscar_demo15.properties.e rb:
Filepath: org/jruby/RubyString.java
Line: 1172
Detail: can't convert nil into String
at /etc/puppet/environments/development/modules/oscar_mysql_tomcat/manifests/context.pp:11:18
on node bcmdit-devel-536-puppetclient Warning: Not using cache on
failed catalog Error: Could not retrieve catalog; skipping run
It is failing at the resolution of #oscar_package, how do I do it the future parser way?
Update 1
After consulting:
https://puppet.com/docs/puppet/5.4/lang_template_erb.html#calling-puppet-functions-from-templates
It seems that I should be using scope.call_function:
<%= scope.call_function('template', [File.dirname(__FILE__) + "/" + "subtemplate_" + #oscar_package + ".properties.erb"]) %>
This yields the same error.
The class I am using is a child of another class with the oscar_package variable defined.
It was solved by passing the variable to the subclass so it could be accessed directly within the scope from where the function in the erb template was called.
So in the init.pp definition the relevant code is:
if $sys_report::active_database_context_list != "" {
oscar_mysql_tomcat::context { "active_${sys_report::active_database_context_list}":
db_name => "$sys_report::active_database_context_list",
oscar_package => "$oscar_package",
oscar_package_build => "$oscar_package_build",
role => "link",
tomcat_site_seal => "$tomcat_site_seal",
tomcat_host_fqdn => "$tomcat_host_fqdn",
tomcat_port => "$tomcat_port",
twitter_feed => "$twitter_feed",
require => File['/etc/sys-report.var'],
}
}

Grouping and Kendo Grid template not working

I have a tab strip inside the details template for my grid. It works fine until I decide to group my data, when I do the details template no longer works. During my investigation it turn out that the Id of the different tab strip has been set to null, while the tab strip that I opened retains their original Id. I am not sure why details template lost reference to the Id. Here are my code below.
Creating the grid
#(Html.Kendo().Grid(Model)
.Name("ChangeLog")
.Columns(columns =>
{
columns.Bound(m => m.ChangeDate2)
.Title("Date and Time")
.ClientTemplate("<span>#= formatUtcDateToLocal(ChangeDate2 ? ChangeDate : '' )#</span>")
.Width("12%");
............................
})
.Filterable()
.Selectable()
.Sortable()
.Groupable()
.Resizable(resize => resize.Columns(true))
.ToolBar(toolbar =>
{
toolbar.Template(
#<text>
<a class="k-button k-button-icontext k-grid-excel" href="#"><span class="k-icon k-i-excel"></span>Export to Excel</a>
</text>
);
})
.Events(e => e.FilterMenuInit("resizeFilter")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Data", "Log")
.Data("buildParam"))
)
.DataBound("preselectCustomFilter"))
.ClientDetailTemplateId("log-details-template")
)
and this is how I define my details template
<script type="text/x-kendo-template" id="change-log-details-template">
<div>
#(Html.Kendo().TabStrip()
.Name("tabStrip_#=Id#")
.Animation(animation => animation.Open(effect => effect.Fade(FadeDirection.In)))
.SelectedIndex(0)
.Items(tabstrip =>
{
tabstrip.Add().Text("Old Value").Content("<div class='oldValue' style='height:137px;padding:10px''><span>#=OldValue#</span></div>");
tabstrip.Add().Text("New Value").Content("<div class='newValue' style='height:137px;padding:10px'><span'>#=NewValue#</span></div>");
}
)
.ToClientTemplate())
</div>
When I inspect the detail template before grouping I see that the Id is being correctly applied
<div class="k-widget k-tabstrip k-header k-floatwrap k-tabstrip-top" id="tabStrip_164317" ...>
After I do the grouping all the template not initialized before the grouping now contains null instead of the id
<div class="k-widget k-tabstrip k-header k-floatwrap k-tabstrip-top" id="tabStrip_null" ........
Any hints on what I need to do? Maybe redraw the grid?
UPDATE
Refreshing the grid via .refresh() did not work.
It was my bad. I needed a second pair of eye. I was using the wrong model. When I made the call to .Read(read => read.Action("Data", "Log") I was returning logModel which is the base model that the model I use inherits from. So on load when I was using the right model it has the Id property, but after the read I was returning the base model which did not, and that is why the Id is null. :D

Drupal preprocess function and session

I set a session var at template preprocess function in a theme I use, but the first time I open the site I cant read the session var, if I refresh the page it works fine, anybody know what can be the problem??
This is the code I use in the preprocess function:
function m_preprocess(&$vars, $hook) {
$default_location = array(
'country_code' => 'ec',
'province_code' => 'p',
'province' => 'Pichincha',
'city' => 'Quito',
'city_path' => 'lugares/u/ec/p/*'
);
if (isset($_COOKIE['proximity_path'])) $default_location['proximity_path'] = $_COOKIE['proximity_path'];
$default_location['path'] = isset($_COOKIE['sort-by']) && $_COOKIE['sort-by']=='proximity'? $_COOKIE['proximity_path'] : $default_location['city_path'];
$_SESSION['location'] = $default_location;
}
A couple of things:
Try dsm($_SESSION); to see what is the var content when the site first load.
I don't know where you create $_COOKIE['proximity_path'], but it is not in the code you show.
Check for typos
The template pre-process function is called before node.tpl.php (that's why it is called pre-process) and that is why the value of the $_SESSION variable is not available in the template preprocess function.
Like you pointed out, it works after the first page load. This happens when only after $_SESSION variable is set in the node body (using the PHP filter)