hiera use hash as variable - puppet

in puppet hiera I have a working construction
location_cfg_append: {allow: "127.0.0.1"
deny: "all"}
Can I replace it by folowing construction?
cf_ips:
allow: "127.0.0.1"
deny: "all"
location_cfg_append: %{hiera('cf_ips')}

When using the hiera lookup function you must use it as a string interpolation function as such the result will be cast to a string, which will likely cause an error. however you can use the alias function which preserves the variable type e.g.
cf_ips:
allow: "127.0.0.1"
deny: "all"
location_cfg_append: "%{alias('cf_ips')}"

Related

How to check UUID using regular expressions?

In order to make validation over a api, i'm send companyId as UUID like: 71158c1a-56fd-4dd4-8e7f-fb95711a41de
To have this validation I used jsonschema with the following patterns (test all 3 of them):
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi
[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}
jsonschema:
companyId: {
type: "string",
default: "",
title: "The companyId Schema",
pattern: "/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$",
examples: ["71158c1a-56fd-4dd4-8e7f-fb95711a41de"],
},
For some reason the validation returned me errors:
path: Ä 'companyId' Å,
property: 'instance.companyId',
message: 'does not match pattern "/ÜÄ0-9a-fA-FÅä8åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä12å$"',
schema: ä
type: 'string',
default: '',
title: 'The companyId Schema',
pattern: '/ÜÄ0-9a-fA-FÅä8åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä12å$',
examples: ÄArrayÅ
å,
instance: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
name: 'pattern',
argument: '/ÜÄ0-9a-fA-FÅä8åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä12å$',
stack: 'instance.companyId does not match pattern "/ÜÄ0-9a-fA-FÅä8åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä12å$"'
å,
Also im getting these cyrillic letters, maybe this is the reason?
The latest version of JSON Schema supports the uuid format (you may need to explicitly turn on format validation in the implementation, as by default it is supposed to be annotation-only):
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"format": "uuid",
}
Also, you have a stray / in your pattern before the ^ anchor, so your pattern will never match.

Make Map values sensitive in custom Terraform provider

I'm writing a custom Terraform provider, and I have a resource that has an argument that is a map[string]string which may contain sensitive values. I want to make the values sensitive but not the keys. I tried setting the Sensitive attribute of the Elem in the map to true (see example below) but I still get the values printed out the console during the plan phase.
return &schema.Resource{
// ...
Schema: map[string]*schema.Schema{
"sensitive_map": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
// Sensitive: true,
},
},
},
}
Example plan phase output:
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# deploy_project.this will be created
+ resource "my_resource" "this" {
+ sensitive_map = {
+ "key" = "value"
}
+ id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
How can I get the value to be marked as sensitive but not the key?
In the Terraform SDK's current model of sensitivity, there is no way to achieve what you are aiming to achieve. Sensitivity is set for an entire attribute at a time, not for parts of an attribute.
Although the SDK model re-uses *schema.Schema as a possible type for Elem as a convenience, in practice only a small subset of the schema.Schema fields can work in that position, because a declaration like this is roughly the same as declaring a variable like the following in a Terraform module:
variable "sensitive_map" {
type = map(string)
sensitive = true
}
Notice that the "sensitive" concept applies to the variable as a whole. It isn't a part of the variable's type constraint, so there isn't any way to write down "map of sensitive strings" as a type constraint. Although provider arguments are not actually module variables, they do still participate in the same system of values and types that variables do, and so have a similar set of capabilities.
I ended settling for a solution using nested blocks rather than a simple map. The schema definition is more complex than a simple map and it makes for a userland configuration that is more verbose but it does satisfy my initial requirements quite well.
"sensitive_map": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"value": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
And it shows up in the plan phase as:
+ resource "my_resource" "this" {
+ sensitive_map {
+ key = "foo"
+ value = (sensitive value)
}
}
It changes the representation in Go from a map[string]string to a map[string]interface{} where the empty interface is itself a map[string]string. In the Create hook of the resource, this is what the code looks like to parse the input config:
sensitiveMap := make(client.EnvVars)
tmp := d.Get("sensitive_map").([]interface{})
for _, v := range tmp {
keyval := v.(map[string]interface{})
vars[keyval["key"].(string)] = keyval["value"].(string)
}
I'm sure it could be optimized further but for now it works just fine!

AWS Cloudformation: How to reuse bash script placed in user-data parameter when creating EC2?

In Cloudformation I have two stacks (one nested).
Nested stack "ec2-setup":
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Parameters" : {
// (...) some parameters here
"userData" : {
"Description" : "user data to be passed to instance",
"Type" : "String",
"Default": ""
}
},
"Resources" : {
"EC2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"UserData" : { "Ref" : "userData" },
// (...) some other properties here
}
}
},
// (...)
}
Now in my main template I want to refer to nested template presented above and pass a bash script using the userData parameter. Additionally I do not want to inline the content of user data script because I want to reuse it for few ec2 instances (so I do not want to duplicate the script each time I declare ec2 instance in my main template).
I tried to achieve this by setting the content of the script as a default value of a parameter:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters" : {
"myUserData": {
"Type": "String",
"Default" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash \n",
"yum update -y \n",
"# Install the files and packages from the metadata\n",
"echo 'tralala' > /tmp/hahaha"
]]}}
}
},
(...)
"myEc2": {
"Type": "AWS::CloudFormation::Stack",
"Properties": {
"TemplateURL": "s3://path/to/ec2-setup.json",
"TimeoutInMinutes": "10",
"Parameters": {
// (...)
"userData" : { "Ref" : "myUserData" }
}
But I get following error while trying to launch stack:
"Template validation error: Template format error: Every Default
member must be a string."
The error seems to be caused by the fact that the declaration { Fn::Base64 (...) } is an object - not a string (although it results in returning base64 encoded string).
All works ok, if I paste my script directly into to the parameters section (as inline script) when calling my nested template (instead of reffering to string set as parameter):
"myEc2": {
"Type": "AWS::CloudFormation::Stack",
"Properties": {
"TemplateURL": "s3://path/to/ec2-setup.json",
"TimeoutInMinutes": "10",
"Parameters": {
// (...)
"userData" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash \n",
"yum update -y \n",
"# Install the files and packages from the metadata\n",
"echo 'tralala' > /tmp/hahaha"
]]}}
}
but I want to keep the content of userData script in a parameter/variable to be able to reuse it.
Any chance to reuse such a bash script without a need to copy/paste it each time?
Here are a few options on how to reuse a bash script in user-data for multiple EC2 instances defined through CloudFormation:
1. Set default parameter as string
Your original attempted solution should work, with a minor tweak: you must declare the default parameter as a string, as follows (using YAML instead of JSON makes it possible/easier to declare a multi-line string inline):
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
myUserData:
Type: String
Default: |
#!/bin/bash
yum update -y
# Install the files and packages from the metadata
echo 'tralala' > /tmp/hahaha
(...)
Resources:
myEc2:
Type: AWS::CloudFormation::Stack
Properties
TemplateURL: "s3://path/to/ec2-setup.yml"
TimeoutInMinutes: 10
Parameters:
# (...)
userData: !Ref myUserData
Then, in your nested stack, apply any required intrinsic functions (Fn::Base64, as well as Fn::Sub which is quite helpful if you need to apply any Ref or Fn::GetAtt functions within your user-data script) within the EC2 instance's resource properties:
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
# (...) some parameters here
userData:
Description: user data to be passed to instance
Type: String
Default: ""
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
UserData:
"Fn::Base64":
"Fn::Sub": !Ref userData
# (...) some other properties here
# (...)
2. Upload script to S3
You can upload your single Bash script to an S3 bucket, then invoke the script by adding a minimal user-data script in each EC2 instance in your template:
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
# (...) some parameters here
ScriptBucket:
Description: S3 bucket containing user-data script
Type: String
ScriptKey:
Description: S3 object key containing user-data script
Type: String
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
UserData:
"Fn::Base64":
"Fn::Sub": |
#!/bin/bash
aws s3 cp s3://${ScriptBucket}/${ScriptKey} - | bash -s
# (...) some other properties here
# (...)
3. Use preprocessor to inline script from single source
Finally, you can use a template-preprocessor tool like troposphere or your own to 'generate' verbose CloudFormation-executable templates from more compact/expressive source files. This approach will allow you to eliminate duplication in your source files - although the templates will contain 'duplicate' user-data scripts, this will only occur in the generated templates, so should not pose a problem.
You'll have to look outside the template to provide the same user data to multiple templates. A common approach here would be to abstract your template one step further, or "template the template". Use the same method to create both templates, and you'll keep them both DRY.
I'm a huge fan of cloudformation and use it to create most all my resources, especially for production-bound uses. But as powerful as it is, it isn't quite turn-key. In addition to creating the template, you'll also have to call the coudformation API to create the stack, and provide a stack name and parameters. Thus, automation around the use of cloudformation is a necessary part of a complete solution. This automation can be simplistic ( bash script, for example ) or sophisticated. I've taken to using ansible's cloudformation module to automate "around" the template, be it creating a template for the template with Jinja, or just providing different sets of parameters to the same reusable template, or doing discovery before the stack is created; whatever ancillary operations are necessary. Some folks really like troposphere for this purpose - if you're a pythonic thinker you might find it to be a good fit. Once you have automation of any kind handling the stack creation, you'll find it's easy to add steps to make the template itself more dynamic, or assemble multiple stacks from reusable components.
At work we use cloudformation quite a bit and are tending these days to prefer a compositional approach, where we define the shared components of the templates we use, and then compose the actual templates from components.
the other option would be to merge the two stacks, using conditionals to control the inclusion of the defined resources in any particular stack created from the template. This works OK in simple cases, but the combinatorial complexity of all those conditions tends to make this a difficult solution in the long run, unless the differences are really simple.
Actually I found one more solution than already mentioned. This solution on the one hand is a little "hackish", but on the other hand I found it to be really useful for "bash script" use case (and also for other parameters).
The idea is to create an extra stack - "parameters stack" - which will output the values. Since outputs of a stack are not limited to String (as it is for default values) we can define entire base64 encoded script as a single output from a stack.
The drawback is that every stack needs to define at least one resource, so our parameters stack also needs to define at least one resource. The solution for this issue is either to define the parameters in another template which already defines existing resource, or create a "fake resource" which will never be created becasue of a Condition which will never be satisified.
Here I present the solution with fake resource. First we create our new paramaters-stack.json as follows:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Outputs/returns parameter values",
"Conditions" : {
"alwaysFalseCondition" : {"Fn::Equals" : ["aaaaaaaaaa", "bbbbbbbbbb"]}
},
"Resources": {
"FakeResource" : {
"Type" : "AWS::EC2::EIPAssociation",
"Condition" : "alwaysFalseCondition",
"Properties" : {
"AllocationId" : { "Ref": "AWS::NoValue" },
"NetworkInterfaceId" : { "Ref": "AWS::NoValue" }
}
}
},
"Outputs": {
"ec2InitScript": {
"Value":
{ "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash \n",
"yum update -y \n",
"# Install the files and packages from the metadata\n",
"echo 'tralala' > /tmp/hahaha"
]]}}
}
}
}
Now in the main template we first declare our paramters stack and later we refer to the output from that parameters stack:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"myParameters": {
"Type": "AWS::CloudFormation::Stack",
"Properties": {
"TemplateURL": "s3://path/to/paramaters-stack.json",
"TimeoutInMinutes": "10"
}
},
"myEc2": {
"Type": "AWS::CloudFormation::Stack",
"Properties": {
"TemplateURL": "s3://path/to/ec2-setup.json",
"TimeoutInMinutes": "10",
"Parameters": {
// (...)
"userData" : {"Fn::GetAtt": [ "myParameters", "Outputs.ec2InitScript" ]}
}
}
}
}
Please note that one can create up to 60 outputs in one stack file, so it is possible to define 60 variables/paramaters per single stack file using this technique.

Allow swagger query param to be array of strings or integers

In building a rest api using swagger2 (openAPI), I want to allow a query param station_id to support the following:
?station_id=23 (returns station 23)
?station_id=23,45 (returns stations 23 and 45)
?station_id=[3:14] (returns stations 3 through 14)
?station_id=100% (%s act as wildcards so returns things like 1001,
10049, etc..)
I use the following swagger definition (an array of strings) as an attempt to accomplish this:
parameters:
- name: station_id
in: query
description: filter stations by station_id
required: false
type: array
items:
type: string
With this definition all of the previous examples work except ?station_id=23 as swagger validation fails with the following message:
{
"message": "Validation errors",
"errors": [
{
"code": "INVALID_REQUEST_PARAMETER",
"errors": [
{
"code": "INVALID_TYPE",
"params": [
"array",
"integer"
],
"message": "Expected type array but found type integer",
"path": [],
"description": "filter stations by station_id"
}
],
"in": "query",
"message": "Invalid parameter (station_id): Value failed JSON Schema validation",
"name": "station_id",
"path": [
"paths",
"/stations",
"get",
"parameters",
"0"
]
}
]
}
note that if I quote the station_id like ?station_id='23' validation passes and I get a correct response. But I'd really prefer not to have to use quotes. Something like a union type would help solve this, but as far as I can tell they aren't supported.
I also have another endpoint /stations/{id} that can handle the case of a single id, but still have many other (non primary key) numerical fields that I want to filter on in the way specified above. For instance station_latitude.
Any ideas to a work around - maybe I can use pattern (regex) somehow? If there is no workaround in the swagger definition is there a way to tweak or bypass the validator? This is a nodejs project using swagger-node I've upgraded the version of swagger-express-mw to 0.7.0.
I think what you'd need is the anyOf or oneOf keyword similar to the one provided by JSON Schema so that you could define the type of your station_id parameter to be either a number or a string. anyOf and oneOf are supported in OpenAPI 3.0 but not in 2.0. An OpenAPI 3.0 definition would look like this:
openapi: 3.0.0
...
paths:
/something:
get:
parameters:
- in: query
name: station_id
required: true
explode: false
schema:
oneOf:
- type: integer # Optional? Array is supposed to cover the use case with a single number
example: 23
- type: array
items:
type: integer
minItems: 1
example: [23, 45]
- type: string
oneOf:
- pattern: '^\[\d+:\d+]$'
- pattern: '^\d+%$'
# or using a single pattern
# pattern: '^(\[\d+:\d+])|(\d+%)$'
example: '[3:14]'
As an alternative, perhaps you could add sortBy, skip, and limit parameters to allow you to keep the type uniform. For example: ?sortBy=station_id&skip=10&limit=10 would retrieve only stations 10 - 20.

Convert Heira variable to comma separated token

I have a yaml file where I can specify n number of options:
---
solr:
- dev
- test
I then call them into a puppet variable using heira:
if $solr_values == undef {
$solr_values = hiera('solr', false)
}
if count($solr_values) > 0 {
class { solr:
cores => [ $solr_values ],
}
}
However $solr_values is coming through as 'devtest' and not 'dev'. 'test' as I'd expect given that it's a list in yaml. Can someone advise on the best approach here?
The expression [ $solr_values ] gives you an array of arrays, e.g. [ [ 'dev', 'test', ... ] ], which is likely not what you want.
I suggest plain
cores => $solr_values,
Note that when you use the array variable $core/$solr_values in a string, e.g.
$debug = "VALUES: '$solr_values'"
Puppet will coerce the array into a string by simply concatenating the values, so you will still end up with 'devtest...'
What you want to do is make use of the join function from the stdlib module, e.g.
cores => join($solr_values, ','),

Resources