Write same template to two different files, changing one value - templates

I would like to write the same Ansible template to two different files, one with a value in the file set to True, and the other with a value set to False.
What's the best way to do this? My instinct was to try and pass a value in the template: directive. However, it seems like this is frowned upon.
One way would be to have two different jinja files with almost entirely the same contents; one has the value set to True and the other False.
Another way would be to define a variable, write one template, then use set_fact to change the variable's value, then write the second file. This also seems a little cumbersome.
Another would be to have the template detect what filename it's being rendered as, somehow? And branch in the template based on that.
I must be missing something obvious.

With Ansible 2.x you can use vars: with tasks:
---
- hosts: localhost
tasks:
- template: src=my_template.j2 dest=out1.txt
vars:
name: John
- template: src=my_template.j2 dest=out2.txt
vars:
name: Jane

Related

Storing parameterized values in cloud formation and referencing it

Is there a way to store variables in Cloudformation?
I've created a resource with a name which is a stage specific name in the following form:
DeliveryStreamName: {'Fn::Sub': ['firehose-events-${Stage}', 'Stage': {'Ref' : 'Stage' }]}
Now if I've to create a cloudwatch alarm on that resource I'm again following the same pattern:
Dimensions:
- Value: {'Fn::Sub': ['firehose-events-${Stage}', 'Stage': {'Ref' : 'Stage' }]}
Instead if I could store the whole value in one variable, it would be much easier for me to refer it.
I thought initially storing it in parameters, like this:
Parameters:
FirehoseEvent: {Type:String, Default: 'firehose-events-${Stage}'}
But the stage value doesn't seem to get passed in here. And there is no non default value either for this resource name.
The other option I considered was using mapping, but that defeats the purpose of using ${Stage}.
Is there some other way which I've missed?
Sadly you haven't missed anything. Parameters can't reference other parameters in their definition.
The only way I can think of doing what you which would be through a custom macro. In its simplest form the macro would just perform traditional find-and-replace type of template processing.
However, the time required to develop such macro could be not worth its benefits, at least in this simple example you've provided in the question.

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.

Explain how `<<: *name` makes a reference to `&name` in docker-compose?

Trying to understand how the docker-compose file was created as I want to replicate this into a kubernetes deployment yaml file.
In reference to a cookiecutter-django's docker-compose production.yaml file:
...
services:
django: &django
...
By docker-compose design, the name of service here is already defined as django but then I noticed this extra bit &django. This made me wonder why its here. Further down, I noticed the following:
...
celeryworker:
<<: *django
...
I don't understand how that works. The docker-compose docs have no reference or mention for using << let alone, making a reference to a named service like *django.
Can anyone explain how the above work and how do I replicate it to a kubernetes deployment or services yaml file (or both?) if possible?
Edit:
The question that #jonsharpe shared was similar but the answer wasn't clear to me on how its used.
There are three different things happening, and none of them are specifically compose syntax, rather they are yaml syntax.
First is defining an anchor with the & followed by a name. That's similar to defining a variable to use later in the yaml, with the value matching the value of the yaml object where it appears.
Next is the alias, specified with * and the same name as the anchor. That uses the anchor in the second location in the yaml file.
Last is a mapping merge using the << syntax, which merges all of the mapped values in the alias with the rest of the values in the current map, allowing you to override values in the saved anchor with values specific to that section of the compose file.
To dig more into this, try searching on "yaml anchors and aliases". The first hit for me is this blog post: https://medium.com/#kinghuang/docker-compose-anchors-aliases-extensions-a1e4105d70bd

Google Deployment Manager - BigTable example

I have been trying this example provided in the Google's Deployment Manager GitHub project.
It works, yet I am not sure what is the purpose of creating three instances named instance_create, instance_update and instance_delete.
For example, taken from the link:
instance_create = {
'name':
'instance_create',
'action':
'gcp-types/bigtableadmin-v2:bigtableadmin.projects.instances.create',
'properties': {
'parent': project_path,
'instanceId': instance_name,
'clusters': copy.deepcopy(initial_cluster),
'instance': context.properties['instance']
},
'metadata': {
'runtimePolicy': ['CREATE']
}
}
What is the purpose of `action` and `metadata`.`runtimePolicy`? I have tried to find it in the documentation but failed miserably.
Why there are three `BigTable` instances there?
You are right, the documentation is missing the information, which would answer your questions regarding these parameters.
However, it helps knowing what's going on in the Depoyment Manager example you linked.
First of all, the following line in the config.yaml is where the things get tricky:
resources:
- name: my-bigtable
type: bigtable.py
This line will do a call to the bigtable.py python file, which sets the resource type of the deployment to that which are in it, under the GenerateConfig function. See how this is done here.
The resources are returned as {'resources': resources} at the end of it, being the resources variable a list of templates created there.
These templates have different name identifiers, which are set by the "name" tag.
So you are not creating three different instances with the name of instance_create, instance_update and instance_delete in this file, but you are creating three templates with those names, that will later be appended to the resources list, and later returned to the config.yaml resources.type tag.
These templates then will be sequentially build and executed by the deployment manager, once the create command is used. Note that they might appear out of order, this is due not using a schema.
It's easier to see this structure in a .yaml file format, for example, built with jinja, the template you posted would be:
resources:
- action: gcp-types/bigtableadmin-v2:bigtableadmin.projects.instances.create
name: instance_create
metadata:
runtimePolicy:
- CREATE
properties:
clusters:
initial:
defaultStorageType: HDD
location: projects/<PROJECT_ID>/locations/<PROJECT_LOCATION>
serveNodes: 4
instance:
displayName: My BigTable Instance.
type: PRODUCTION
instanceId: my-instance
parent: projects/<PROJECT_ID>
Notice that the parameters under properties are the fields in the request body to bigtableadmin.projects.instances.create (which is nesting a clusters object parameters and a instance object parameters). Note that the InstanceId under properties is always the same, hence the BigTable instance, on which the templates do the calls, is always the same one.
The thing is that, not only the example you linked creates various templates to be run in the same script, but that the resource type for each template is a call to the BigTable API.
Normally the template resources are specified with the type tag, but since you are calling a resource that is directly running an API call (i.e. instead of just specifying gcp-types/bigtableadmin-v2, you are specifying bigtableadmin-v2:bigtableadmin.projects.instances.create), the action tag is used. I haven't found this difference on usage documented anywhere, but it needs to be specified like that.
You will know if you are calling an API 'endpoint' directly if the resource ends with either create/update/delete.
Finally, the I have investigated in my side, and the metadata.runtimePolicy is tied to the fact that the resource type is an API call (like in the previous point). Once again, I haven't found this documented anywhere.
However, since this is a requirement, you will always have to set the correct value in this field. It basically boils down to have metadata.runtimePolicy set to this values, depending on which type of API call you do:
create -> ['CREATE']
update -> ['UPDATE_ON_CHANGE']
delete -> ['DELETE']
Summarizing:
You are not creating three different instances, but three different templates, which do the work on the same BigTable instance.
You need to change the resource type flag to action if you are calling an API endpoint (create/update/delete), instead of just naming the base API.
The metadata.runtimePolicy value is a requirement when doing a call to one of the aforenamed endpoints.

SAM template environment variables use map, list, associative array?

I've only seen examples with single values in SAM templates:
Environment:
Variables:
TABLE_NAME: my-table
I want to do something like this but doesn't seem to work:
Environment:
Variables:
myVar:
- prop1: aaa
prop2: sdfsdfsd
prop3: ssss
- prop1: bbb
prop2: wwwwww
prop3: aaaaa
I want to have an environment variable that is like a list of objects. I could store a delimited string and parse it myself but I'd prefer to have it be like an object/map/list like if I'm ready a YAML file.
The closest you can do is to json encode the value for your environmental variable
and decode it using the runtime language:
Environment:
Variables:
USER: '{"name": "john", "surname": "galt"}'
If you want to prevent decoding json on each request, move your decoding logic outside the handler, in this case code won't be re-executed while lambda is hot.
Any declarations in your Lambda function code (outside the handler code, see Programming Model) remains initialized, providing additional optimization when the function is invoked again. For example, if your Lambda function establishes a database connection, instead of reestablishing the connection, the original connection is used in subsequent invocations. We suggest adding logic in your code to check if a connection exists before creating one.
Read about lambda execution model
I personally would create a json file, store it in s3 bucket and use an environment variable to specify s3 url to that file. Additionally, use the same technique I mentioned above or use even more complicated caching mechanism depending on the situation when retrieving the config file