Using template to set a variable in chef - templates

new to chef and trying to pass a long list of variables to a batch file run. Have thought of writing a list of these in a template and calling the template in the recipe i.e:
options = template "optionstemplate"
How does one set a variable using hashes from a template of in chef? Please do let me know if this is possible of if there is another way to do this.

While technically doable, this is very hard and not recommended. You should instead write some Ruby code to generate the options string you need. Maybe something like:
options = ''
node['mythingy']['options'].each do |key, value|
options << " --#{key}=#{value}"
end

Related

How to automate M2Doc generation including the settings?

I've applied the guidance on programmatic usage of M2Doc (also with this help) to successfully generate a document via the API, which was previously prepared by using the M2Doc GUI (configured .docx plus a .genconf file). It seems to also work with a configured .docx, but without a .genconf file.
Now I would like to go a step further and ease the user interface in our application. The user should come with a .docx, include the {m:...} fields there, especially for variable definition, and then in our Eclipse application just assign model elements to the list of variables. Finally press "generate". The rest I would like to handle via the M2Doc API:
Get list of variables from the .docx
Tell M2Doc the variable objects (and their types and other required information, if that is separately necessary)
Provide M2Doc with sufficient information to handle AQL expressions like projectmodel::PJDiagram.allInstances() in the Word fields
I tried to analyse the M2Doc source code for this, but have some questions to achieve the goal:
The parse/generate API does not create any config information into the .docx or .genconf files, right? What would be the API to at least generate the .docx config information?
The source code mentions "if you are using a Generation" - what is meant with that? The use of a .genconf file (which seems to be optional for the generate API)?
Where can I get the list of variables from, which M2Doc found in a .docx (during parse?), so that I can present it to the user for Object (Model Element) assignment?
Do I have to tell M2Doc the types of the variables, and in which resource file they are located, besides handing over the variable objects? My guess is no, as using a blank .docx file without any M2Doc information stored also worked for the variables themselves (not for any additional AQL expressions using other types, or .oclAsType() type castings).
How can I provide M2Doc with the types information for the AQL expressions mentioned above, which I normally tell it via the nsURI configuration? I handed over the complete resourceSet of my application, but that doesn't seem to be enough.
Any help would be very much appreciated!
To give you an impression of my code so far, see below - note that it's actually Javascript instead of Java, as our application has a built-in JS-Java interface.
//=================== PARSING OF THE DOCUMENT ==============================
var templateURIString = "file:///.../templateReqs.docx";
var templateURI = URI.createURI(templateURIString);
// canNOT be empty, as we get nullpointer exceptions otherwise
var options = {"TemplateURI":templateURIString};
var exceptions = new java.util.ArrayList();
var resourceSetForModels = ...; //here our application's resource set for the whole model is used, instead of M2Doc "createResourceSetForModels" - works for the moment, but not sure if some services linking is not working
var queryEnvironment = m2doc.M2DocUtils.getQueryEnvironment(resourceSetForModels, templateURI, options);
var classProvider = m2doc.M2DocPlugin.getClassProvider();
// empty Monitor for the moment
var monitor = new BasicMonitor();
var template = m2doc.M2DocUtils.parse(resourceSetForModels.getURIConverter(), templateURI, queryEnvironment, classProvider, monitor);
// =================== GENERATION OF THE DOCUMENT ==============================
var outputURIString = "file:///.../templateReqs.autogenerated.docx";
var outputURI = URI.createURI(outputURIString);
variables["myVar1"] = ...; // assigment of objects...
m2doc.M2DocUtils.generate(template, queryEnvironment, variables, resourceSetForModels, outputURI, monitor);
Thanks!
No the API used to parse an generate don't modifies the template file nor the .genconf file. To modify the configuration of the template you will need to use the
TemplateCustomProperties class. That will allow you to register your metamodels and service classes. This instormation is then used to configure the IQueryEnvironment, so you might also want to directly configure the IQueryEnvironment in your code.
The generation in this context referes to the .genconf file. Note The genconf file is also an EMF model, so you can also craft one in memory to launch you generation if it's easier for you. But yes the use of a .genconf file is optional like in your code example.
To the list of variables in the template you can use the class TemplateCustomProperties:
TemplateCustomProperties.getVariables() will list the variables that are declared with their type
TemplateCustomProperties.getMissingVariables() to list varaibles that are used in the template but not declared
You can also find le list of used metamodels (EPackage nsURIs) and imported services classes.
The type of variables is not needed at generation time, it's only needed if you want to validate your template. At generation time you need to pass a map from the variable name to its value as you did in your example. The value of a variable can be a any object from your model (an EObject), a String, an Integer, ... If you want to use something like oclIsKindOf(pkg::MyEClass) you will need to register the nsURI of pkg first see the next point.
The code you provided should let you use something like projectmodel::PJDiagram.allInstances(). This service needs a ResourceSetRootEObjectProvider() that is initialized in M2DocUtils.getQueryEnvironment(). But you need to declare the nsURI of your metamodel in your template (see TemplateCustomProperties). This will register it in the IQueryEnvironment. You can also register it yourself using IQueryEnvironment.registerEPackage().
This should help you finding the missing parts in the configuration of the AQL environment. Your code seems good and should work when you add the configuration part.

Rendering from strings instead of files with MarkoJS

I'm using markojs for my emails templates but now we are moving these templates inside our database to edit them online.
We still need to use marko to keep our full HTML structure and variables behavior aswell.
I've found 2 ways to get templates as string like renderSync() method but it need the template to exist as file before or with compile() but I don't know how to make it work with variables handling.
You can use Marko's load method to compile templates and get back the template instance which you can then render to get the final HTML:
const template = require("marko").load(templatePath, templateSource, compilerOptions);
const html = template.renderSync(data);
You probably don't need to pass any custom compilerOptions and can omit the last argument.
Even though your template doesn't exist on disk, you still need to pass a templatePath to a real directory with a dummy .marko file. For instance you could do this:
const templatePath = path.join(__dirname, `${database.id}.marko`);
The templatePath is used for two purposes:
As a key for node's require cache. If you request to compile the same filename multiple times, you will get the original compilation. This might mean you need to purge the require cache when a template is edited: delete require.cache[templatePath];
To discover custom Marko tags. If you have custom tags/components that are intended to be used by the email templates, you should make sure that the path specified by templatePath allows those tags to be discovered.

IntelliJ Custom Template Variable

I am trying to create my custom template with a custom variable called $MyName. And I think it should be possible for IntelliJ to ask about the variable's value if it was not initialized. In the documentation they provide some informations about how to do this, but they don't have a real example. They just say, it somehow IntelliJ Idea will ask me to specify it.
If, when applying a template, the values of certain template variable
are not known, IntelliJ IDEA will ask you to specify them.
How can I create a custom variable like $MyName and then when the user uses the template, it will ask him what his name is?
IntelliJ IDEA 2016.1 Documentation
Edit (19.04.2016): Added Screenshots
As you can see, the custom variable is not recognized or not valid. If I declare it like ${MyName}, it won't work either.
It's a bug in IntelliJ IDEA, filed as https://youtrack.jetbrains.com/issue/IDEA-154958. Thanks for noticing!
File Template Variables
File | Settings | Editor | File and Code Templates
You should set it in files. If set in includes, the new file is directly output variable name instead of variable content. For example, set the Java Class file Custom variable$DESCRIPTION.If the value of a variable is not defined in the template, IntelliJ IDEA will ask you to specify it when the template is applied.
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
/**
* Description: $DESCRIPTION
* Created by ${USER}
* Date: ${YEAR}/${MONTH}/${DAY}
* Time: ${TIME}
*/
public class ${NAME} {
}
you can also define the values of custom variables right in the template using the #set directive.
For example, if you want to use your full name instead of your login name defined through the predefined variable ${USER}, use the following construct:
#set( $MyName = "John Smith" )
Reference link
File Template Variables

How to test templates with hiera data locally?

I'm trying to figure out a way to take a erb template file and use hiera data (even from a single yaml file) and just use the template to generate a file with replaced values.
Have you ever tried anything like this? My first thought is to write a ruby script, but maybe there's a simpler solution.
Thanks in advance.
Edit:
Since it might not be clear, let me explain the use case.
I want all application configuration to be templated and committed by developers and I want to provide them an automated way of filling those templates in on their local machines (laptops) without using puppet. The extra benefit is validation of templates before actually committing them.
I'm not sure why you would want to do this from hiera data directly, but it would be easy to implement with the ERB and yaml ruby libs. Something like (psudo-code):
class Erbwritter
require 'erb'
require 'yaml
attr_accessor :output_path, :yaml_path
def initialize(template, command)
#output = :output_path
#data = :yaml_path
.....
end
def render()
ERB.new(#template).result(binding)
end
def save(file)
File.open(file, "w+") do |f|
f.write(render)
end
end
def parse_yaml(#data)
File.open(#data, ...
# parse some stuff, add them to a local {}
end
end
Then, you can instance this class like:
newTemplate = Erbwritter.new(/path/to/output, /path/to/yaml)
newTemplate.save(File.join(Dir.pwd, your_file_name"))
Again, this is all basically psudo code and won't work out of the box, but it's pretty close. So have fun.
You can read more about ERB Class here.

Django Template set of sets

Is it possible to access a set of a set in django template.
ie. a.b_set.c_set.count
so it gets a count of all c objects related to all b objects which are related to c.
I know I can make a query in the backend ie c.objects.filter(b__a=a), however I wish to do it from the template alone.
Cheers,
Emmet
This may not be possible to do from the template, since it was never intended to use "complex" logic. You should do it in the view.
Since what you want to get is a new attribute "per queryset", this is no one-liner.
Example:
as = a.objects.all()
for a in as:
a.b_c_count = c.objects.filter(b__a=a).count()
And use it like that in the template:
a.b_c_count
If you have a lot of a objects, this will be a bottleneck, so you may want to try the extra method (and use as = a.objects.all().extra(*parameters)), or even raw sql.