I’m building a script that utilizes a config file (YAML) to read in all the necessary configuration information, then prints out all the necessary steps a Linux Admin needs to step through to build a server.
A required option is for the Linux Admin that’s running the script to be able to override any of the item/value pairs from the config file, at the command-line.
The way I’m currently handling this seems overly cumbersome and I know there’s got to be a more innovative and less clunky way to do this.
In the code I:
-
Parse the YAML config file with YAML::Tiny
location: continent: na country: us city: rh -
Create variables with the same names as the config file items, assigning the values from the config file.
my $yaml = YAML::Tiny->new; $yaml = YAML::Tiny->read($config_yml); my $continent = $yaml->[0]->{location}->{continent}; my $country = $yaml->[0]->{location}->{country}; my $city = $yaml->[0]->{location}->{city}; -
Use Getopt::Long and assign the variables, overriding anything passed at the command-line.
GetOptions ( "city=s" => \$city, "continent=s" => \$continent, "country=s" => \$country, );
So those are just 3 item/values pairs, my actual config has over 40 and will change…Which makes for a bit of work to have to keep updating. Any suggestions?
You can let the admin override the YAML settings with a single, flexible switch similar to what
ssh(1)does with-o. This is especially appropriate if the config settings are numerous and likely to change.Now, inside the script, you might keep all your runtime config bundled together in a hash for convenience (rather than having
$this_and_that_optscalars proliferate over time). Option parsing would then look something like this:or whatever. You can normalize config keys and values, handle arbitrarily deep key/subkey/subkey configs, etc. This can get slippery, so you might like to key-lock that global hash.