Puppet - Duplicate declaration for Registry_key - powershell

I have a manifest file to add registry keys and values based on facts (works fine).
registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
ensure => present,
}
registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
ensure => present,
type => dword,
data => $test_key_value,
}
I want to add a second file to remove these if required but when i do i get an error
"Duplicate declaration: Registry_key[HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate] is already declared"
Not sure how to get around this - if at all? Any advice appreciated. Obviously a puppet novice...
Thanks

If you want to solve this problem, you would probably use custom or external facts, something like this:
$ensure = $facts['include_windows_update_keys']
registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
ensure => $ensure,
}
registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
ensure => $ensure,
type => dword,
data => $test_key_value,
}
As you have discovered, declaring the same resource more than once but with different attributes is not allowed in Puppet.
There is more on custom facts here in the docs.

In most situations Alex's suggestion is the way I'd proceed. Usually the best way, to default it in common.yaml and override based on node name or another level in hiera. Depending on your use case, a less straight-forward way is to wrap those blocks in a conditional (if/unless/else) where it's present/absent depending on a boolean set in hiera. Something along the lines of unless $exclude_from_testkey or a case statement. Let me know if you're new to hiera and/or parameterization.

You have resource declarations for specifying that a particular registry key and value should be ensured present on the target node. If you also have declarations specifying that one or both should be absent, and Puppet evaluates both sets, then what are you actually telling Puppet to do? It cannot comply with both sets of declarations.
Puppet takes an extremely cautious approach to situations like this, which makes sense given its role in managing infrastructure. In the event that the same resource is declared more than once for the same target, Puppet aborts. This produces practical difficulties from time to time, but I am confident that it has protected many, many systems from misconfiguration.
The solution is to ensure that your manifest set declares only one set of those declarations for each node. You could do that by having only one set, and twiddling their $ensure parameters dynamically, as #AlexHarvey suggests. You could also do it by putting the two sets of declarations in different blocks, and selecting between them with conditional statements. Or you could put them in altogether different classes, and be certain to include just one of them for each node.
But I have to differ with Alex here on the specifics. I would not typically use a custom fact here, because that gives control over which option is exercised to the client. Generally speaking, I want the master to dictate questions of how various nodes are configured. For this purpose, it is a pretty common idiom to use a class parameter to control whether the resources are ensured present or absent:
class mymodule::windows_update(
Enum['absent','present'] $ensure = $present,
$test_key_value
) {
registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
ensure => $ensure,
}
registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
ensure => $ensure,
type => dword,
data => $test_key_value,
}
}

Related

Unique symbol value on type level

Is it possible to have some kind of unique symbol value on the type level, that could be used to distinct (tag) some record without the need to supply a unique string value?
In JS there is Symbol often used for such things. But I would like to have it without using Effect, in pure context.
Well, it could even like accessing Full qualified module name (which is quite unique for the task), but I'm not sure if this is a really relevant/possible thing in the Purescript context.
Example:
Say There is some module that exposes:
type Worker value state =
{ tag :: String
, work :: value -> state -> Effect state
}
makeWorker :: forall value state. Worker value state
performWork :: forall value state. woker -> Worker value state -> value -> Unit
This module is used to manage the state of workers, it passes them value and current state value, and gets Effect with new state value, and puts in state map where keys are tags.
Users of the module:
In one module:
worker = makeWorker { tag: "WorkerOne", work }
-- Then this tagged `worker` is used to performWork:
-- performWork worker "Some value"
In another module we use worker with another tag:
worker = makeWorker { tag: "WorkerTwo", work }
So it would be nice if there would be no need to supply a unique string ("WorkerOne", "WorkerTwo") as a tag but use some "generated" unique value. But the task is that worker should be created on the top level of the module in pure context.
Semantics of PureScript as such is pure and pretty much incompatible with this sort of thing. Same expression always produces same result. The results can be represented differently at a lower level, but in the language semantics they're the same.
And this is a feature, not a bug. In my experience, more often than not, a requirement like yours is an indication of a flawed design somewhere upstream.
An exception to this rule is FFI: if you have to interact with the underlying platform, there is no choice but to play by that platform's rules. One example I can give is React, which uses the JavaScript's implicit object identity as a way to tell components apart.
So the bottom line is: I urge you to reconsider the requirement. Chances are, you don't really need it. And even if you do, manually specified strings might actually be better than automatically generated ones, because they may help you troubleshoot later.
But if you really insist on doing it this way, good news: you can cheat! :-)
You can generate your IDs effectfully and then wrap them in unsafePerformEffect to make it look pure to the compiler. For example:
import Effect.Unsafe (unsafePerformEffect)
import Data.UUID (toString, genUUID)
workerTag :: String
workerTag = toString $ unsafePerformEffect genUUID

How to use Scala Cats Validated the correct way?

Following is my use case
I am using Cats for validation of my config. My config file is in json.
I deserialize my config file to my case class Config using lift-json and then validate it using Cats. I am using this as a guide.
My motive for using Cats is to collect all errors iff present at time of validation.
My problem is the examples given in the guide, are of the type
case class Person(name: String, age: Int)
def validatePerson(name: String, age: Int): ValidationResult[Person] = {
(validateName(name),validate(age)).mapN(Person)
}
But in my case I already deserialized my config into my case class ( below is a sample ) and then I am passing it for validation
case class Config(source: List[String], dest: List[String], extra: List[String])
def vaildateConfig(config: Config): ValidationResult[Config] = {
(validateSource(config.source), validateDestination(config.dest))
.mapN { case _ => config }
}
The difference here is mapN { case _ => config }. As I already have a config if everything is valid I dont want to create the config anew from its members. This arises as I am passing config to validate function not it's members.
A person at my workplace told me this is not the correct way, as Cats Validated provides a way to construct an object if its members are valid. The object should not exist or should not be constructible if its members are invalid. Which makes complete sense to me.
So should I make any changes ? Is the above I'm doing acceptable ?
PS : The above Config is just an example, my real config can have other case classes as its members which themselves can depend on other case classes.
One of the central goals of the kind of programming promoted by libraries like Cats is to make invalid states unrepresentable. In a perfect world, according to this philosophy, it would be impossible to create an instance of Config with invalid member data (through the use of a library like Refined, where complex constraints can be expressed in and tracked by the type system, or simply by hiding unsafe constructors). In a slightly less perfect world, it might still be possible to construct invalid instances of Config, but discouraged, e.g. through the use of safe constructors (like your validatePerson method for Person).
It sounds like you're in an even less perfect world where you have instances of Config that may or may not contain invalid data, and you want to validate them to get "new" instances of Config that you know are valid. This is totally possible, and in some cases reasonable, and your validateConfig method is a perfectly legitimate way to solve this problem, if you're stuck in that imperfect world.
The downside, though, is that the compiler can't track the difference between the already-validated Config instances and the not-yet-validated ones. You'll have Config instances floating around in your program, and if you want to know whether they've already been validated or not, you'll have to trace through all the places they could have come from. In some contexts this might be just fine, but for large or complex programs it's not ideal.
To sum up: ideally you'd validate Config instances whenever they are created (possibly even making it impossible to create invalid ones), so that you don't have to remember whether any given Config is good or not—the type system can remember for you. If that's not possible, because of e.g. APIs or definitions you don't control, or if it just seems too burdensome for a simple use case, what you're doing with validateConfig is totally reasonable.
As a footnote, since you say above that you're interested in looking in more detail at Refined, what it provides for you in a situation like this is a way to avoid even more functions of the shape A => ValidationResult[A]. Right now your validateName method, for example, probably takes a String and returns a ValidationResult[String]. You can make exactly the same argument against this signature as I have against Config => ValidationResult[Config] above—once you're working with the result (by mapping a function over the Validated or whatever), you just have a string, and the type doesn't tell you that it's already been validated.
What Refined allows you to do is write a method like this:
def validateName(in: String): ValidationResult[Refined[String, SomeProperty]] = ...
…where SomeProperty might specify a minimum length, or the fact that the string matches a particular regular expression, etc. The important point is that you're not validating a String and returning a String that only you know something about—you're validating a String and returning a String that the compiler knows something about (via the Refined[A, Prop] wrapper).
Again, this may be (okay, probably is) overkill for your use case—you just might find it nice to know that you can push this principle (tracking validation in types) even further down through your program.

issue while ordering puppet class execution

I have this recursive copy action called through
class first_class{
file{'some name':
ensure => 'directory',
path => '/path/to/here',
owner => 'some_owner',
group => 'some_group',
recurse => remote,
source => 'puppet:///modules/scripts'
}
}
class second_class{
file{'tmp':
ensure => 'present',
path => '/path/to/here/tmp.sh',
owner => 'some_owner',
group => 'some_group',
mode => '0755',
notify => Exec['some_process']
}
}
The files are recursively copied but the content is not. So it seems that the file is recreated by the second_class, however in my main manifest file I have
node default {
Class { 'my_module::first_class':} -> Class { 'my_module::second_class':}
Is there a way to tackle it ?
The files are recursively copied but the content is not. So it seems that the file is recreated by the second_class
Actually, no, that's not quite what is happening. Your second_class contains an explicit declaration of File['tmp']. Each resource can be declared only once, and explicit File declarations take precedence over implicit ones generated for the contents of recursively-managed directories. This is a feature. Thus, the file in question is not being recreated by the explicit declaration; rather, it is being managed only according to that declaration.
Because File['tmp'] uses ensure => present, it accepts any form of file (directory, symlink, regular file, etc.), and if there is no such file at all then it will create an empty ordinary file. That's what you observe. It has nothing to do with order of resource application.
Is there a way to tackle it ?
Yes. If you want the file to be managed via File['some name'] then do not declare an explicit resource for it. If you must declare it explicitly, e.g. so as to set its notify property, then make that declaration reflect the complete desired target-machine state.
Overall, I suspect you might benefit from some refactoring, as the situation has some code smell. Be aware also that recursive file management has always been ... quirky ... at best. It has its uses, but often you are better off with something else.

Not Able to Set Class' Attributes in Role

First off, I'm not really sure how much information is necessary to include because I'm having a really hard time tracing the origin of this problem.
I have a Moose role with a subroutine that (along with a few other things) tries to set the attributes for a class like this:
$genre = Movie::Genre->new({
genreName => 'Drama',
genreID => '1'
});
The problem is, it doesn't. The dump of $genre immediately after, indicates that it's still empty:
$genre: bless( {}, 'Movie::Genre' )
Stranger still, when I execute THE EXACT SAME LINE in my test file, it works as expected with this dump:
$genre: bless( {
genreID => '1',
genreName => 'Drama'
}, 'Movie::Genre' )
I'm struggling to find what makes these two lines of code different, causing one to work and one to fail.
Any ideas as to what conditions would cause the first example to fail and allow the second to succeed? I'd be happy to provide more context if necessary. Thanks!
That line simply passes those parameters to the Movie::Genre constructor. It's up to that constructor to decide what to do with them.
It sounds like that call (in the role) is getting executed before the Movie::Genre class has acquired attributes named genreName and genreID. By default, Moose constructors ignore any parameters they don't recognize, so this doesn't generate a warning.
Your test file must be making that call after the attributes have been added to Movie::Genre.
We'd have to see more of the code to figure out exactly why this is happening.

Perl - Calling subclass constructor from superclass (OO)

This may turn out to be an embarrassingly stupid question, but better than potentially creating embarrassingly stupid code. :-) This is an OO design question, really.
Let's say I have an object class 'Foos' that represents a set of dynamic configuration elements, which are obtained by querying a command on disk, 'mycrazyfoos -getconfig'. Let's say that there are two categories of behavior that I want 'Foos' objects to have:
Existing ones: one is, query ones that exist in the command output I just mentioned (/usr/bin/mycrazyfoos -getconfig`. Make modifications to existing ones via shelling out commands.
Create new ones that don't exist; new 'crazyfoos', using a complex set of /usr/bin/mycrazyfoos commands and parameters. Here I'm not really just querying, but actually running a bunch of system() commands. Affecting changes.
Here's my class structure:
Foos.pm
package Foos, which has a new($hashref->{name => 'myfooname',) constructor that takes a 'crazyfoo NAME' and then queries the existence of that NAME to see if it already exists (by shelling out and running the mycrazyfoos command above). If that crazyfoo already exists, return a Foos::Existing object. Any changes to this object requires shelling out, running commands and getting confirmation that everything ran okay.
If this is the way to go, then the new() constructor needs to have a test to see which subclass constructor to use (if that even makes sense in this context). Here are the subclasses:
Foos/Existing.pm
As mentioned above, this is for when a Foos object already exists.
Foos/Pending.pm
This is an object that will be created if, in the above, the 'crazyfoo NAME' doesn't actually exist. In this case, the new() constructor above will be checked for additional parameters, and it will go ahead and, when called using ->create() shell out using system() and create a new object... possibly returning an 'Existing' one...
OR
As I type this out, I am realizing it is perhaps it's better to have a single:
(an alternative arrangement)
Foos class, that has a
->new() that takes just a name
->create() that takes additional creation parameters
->delete(), ->change() and other params that affect ones that exist; that will have to just be checked dynamically.
So here we are, two main directions to go with this. I'm curious which would be the more intelligent way to go.
In general it's a mistake (design-wise, not syntax-wise) for the new method to return anything but a new object. If you want to sometimes return an existing object, call that method something else, e.g. new_from_cache().
I also find it odd that you're splitting up this functionality (constructing a new object, and returning an existing one) not just into separate namespaces, but also different objects. So in general, you're closer with your second approach, but you can still have the main constructor (new) handle a variety of arguments:
package Foos;
use strict;
use warnings;
sub new
{
my ($class, %args) = #_;
if ($args{name})
{
# handle the name => value option
}
if ($args{some_other_option})
{
# ...
}
my $this = {
# fill in any fields you need...
};
return bless $this, $class;
}
sub new_from_cache
{
my ($class, %args) = #_;
# check if the object already exists...
# if not, create a new object
return $class->new(%args);
}
Note: I don't want to complicate things while you're still learning, but you may also want to look at Moose, which takes care of a lot of the gory details of construction for you, and the definition of attributes and their accessors.
It is generally speaking a bad idea for a superclass to know about its subclasses, a principle which extends to construction.[1] If you need to decide at runtime what kind of object to create (and you do), create a fourth class to have just that job. This is one kind of "factory".
Having said that in answer to your nominal question, your problem as described does not seem to call for subclassing. In particular, you apparently are going to be treating the different classes of Foos differently depending on which concrete class they belong to. All you're really asking for is a unified way to instantiate two separate classes of objects.
So how's this suggestion[3]: Make Foos::Exists and Foos::Pending two separate and unrelated classes and provide (in Foos) a method that returns the appropriate one. Don't call it new; you're not making a new Foos.
If you want to unify the interfaces so that clients don't have to know which kind they're talking about, then we can talk subclassing (or better yet, delegation to a lazily-created and -updated Foos::Handle).
[1]: Explaining why this is true is a subject hefty enough for a book[2], but the short answer is that it creates a dependency cycle between the subclass (which depends on its superclass by definition) and the superclass (which is being made to depend on its subclass by a poor design decision).
[2]: Lakos, John. (1996). Large-scale C++ Software Design. Addison-Wesley.
[3]: Not a recommendation, since I can't get a good enough handle on your requirements to be sure I'm not shooting fish in a dark ocean.
It is also a factory pattern (bad in Perl) if the object's constructor will return an instance blessed into more than one package.
I would create something like this. If the names exists than is_created is set to 1, otherwise it is set to 0.. I would merge the ::Pending, and ::Existing together, and if the object isn't created just put that into the default for the _object, the check happens lazily. Also, Foo->delete() and Foo->change() will defer to the instance in _object.
package Foo;
use Moose;
has 'name' => ( is => 'ro', isa => 'Str', required => 1 );
has 'is_created' => (
is => 'ro'
, isa => 'Bool'
, init_arg => undef
, default => sub {
stuff_if_exists ? 1 : 0
}
);
has '_object' => (
isa => 'Object'
, is => 'ro'
, lazy => 1
, init_arg => undef
, default => sub {
my $self = shift;
$self->is_created
? Foo->new
: Bar->new
}
, handles => [qw/delete change/]
);
Interesting answers! I am digesting it as I try out different things in code.
Well, I have another variation of the same question -- the same question, mind you, just a different problem to the same class:subclass creation issue!
This time:
This code is an interface to a command line that has a number of different complex options. I told you about /usr/bin/mycrazyfoos before, right? Well, what if I told you that that binary changes based on versions, and sometimes it completely changes its underlying options. And that this class we're writing, it has to be able to account for all of these things. The goal (or perhaps idea) is to do: (perhaps called FROM the Foos class we were discussing above):
Foos::Commandline, which has as subclasses different versions of the underlying '/usr/bin/mycrazyfoos' command.
Example:
my $fcommandobj = new Foos::Commandline;
my #raw_output_list = $fcommandobj->getlist();
my $result_dance = $fcommandobj->dance();
where 'getlist' and 'dance' are version-dependent. I thought about doing this:
package Foos::Commandline;
new (
#Figure out some clever way to decide what version user has
# (automagically)
# And call appropriate subclass? Wait, you all are telling me this is bad OO:
# if v1.0.1 (new Foos::Commandline::v1.0.1.....
# else if v1.2 (new Foos::Commandline::v1.2....
#etc
}
then
package Foos::Commandline::v1.0.1;
sub getlist ( eval... system ("/usr/bin/mycrazyfoos", "-getlistbaby"
# etc etc
and (different .pm files, in subdir of Foos/Commandline)
package Foos::Commandline::v1.2;
sub getlist ( eval... system ("/usr/bin/mycrazyfoos", "-getlistohyeahrightheh"
#etc
Make sense? I expressed in code what I'd like to do, but it just doesn't feel right, particularly in light of what was discussed in the above responses. What DOES feel right is that there should be a generic interface / superclass to Commandline... and that different versions should be able to override it. Right? Would appreciate a suggestion or two on that. Gracias.