Skip to content

Instantly share code, notes, and snippets.

@issm
Created August 28, 2011 07:01
Show Gist options
  • Save issm/1176338 to your computer and use it in GitHub Desktop.
Save issm/1176338 to your computer and use it in GitHub Desktop.
+{
network_type => +{qw/
local 192.168.1.152
emobile 192.168.144.152
home 192.168.0.152
/},
rules => [qw/
www.momoco.local %
dev.momoco.local %
foo.momoco.local %
dev.proj1.local %
www.proj2.local %
hoge.example.com aaa.bbb.ccc.ddd
/],
};
#!/usr/bin/env perl
use strict;
use warnings;
use 5.12.0;
sub main {
my ($mode) = @_;
$mode //= 'local';
my $dir_root = '/usr/local/etc/unbound';
my $pid_file = "${dir_root}/unbound.pid";
my $conf_file = "${dir_root}/${mode}.conf";
-f $conf_file or die qq{File does not exist: ${conf_file}};
my $action = -f $pid_file ? 'restart' : 'start';
say sprintf qq{%sing unbound with "%s" mode...}, (ucfirst $action), $mode;
my ($cmd_stop, $cmd_start) = (
"sudo kill -TERM \$(cat ${pid_file})",
"sudo unbound -c ${conf_file}",
);
my $msg;
if ( -f $pid_file ) {
say " % $cmd_stop";
$msg = `$cmd_stop`;
}
say " % $cmd_start";
$msg = `$cmd_start`;
if ( $msg ) {
die "${msg}";
exit 1;
}
else {
say "...done.";
exit 0;
}
}
main (@ARGV);
__END__
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.12.0;
use FindBin;
use Data::Section::Simple qw/get_data_section/;
use Text::MicroTemplate qw/:all/;
use File::Path qw/make_path/;
my $DIR_ROOT = '/usr/local/etc/unbound';
sub fix_rules {
my ($rules, $ip_base) = @_;
my $ret = [];
while ( @$rules ) {
my ($hostname, $ip);
$hostname = shift @$rules;
next if $hostname =~ /^(#|[-=]{2,})/; # "#" "--" "==" で始まる行はスキップする
$ip = shift @$rules;
$ip = $ip_base if $ip eq '%';
push @$ret, $hostname, $ip;
}
return $ret;
}
sub main {
my ($conf_file) = @_;
$conf_file //= "${DIR_ROOT}/scripts/config.pl";
my $conf = do $conf_file or die $!;
my $dir_inc = "${DIR_ROOT}/include";
make_path $dir_inc unless -d $dir_inc;
my $out_template = get_data_section('hosts.mt');
for my $type ( keys %{ $conf->{network_type} } ) {
my $ip_base = $conf->{network_type}{$type};
my @rules = @{ $conf->{rules} // [] };
my $out = render_mt( $out_template, {
type => $type,
ip_base => $ip_base,
rules => fix_rules( \@rules, $ip_base ),
});
my $f_out = sprintf '%s/%s.hosts', $dir_inc, $type;
open my $fh_out, '>', $f_out or die $!;
print $fh_out $out;
close $fh_out;
say $f_out;
}
exit 0;
}
main(@ARGV);
__DATA__
@@ hosts.mt
<?
my $var = $_[0];
my $ip_base = $var->{ip_base};
my @rules;
?>
local-zone: "local." static
? @rules = @{ $var->{rules} // [] };
? while ( @rules ) {
? my $hostname = shift @rules;
? my $ip = shift @rules;
local-data: "<?= $hostname; ?>. A <?= $ip; ?>"
? }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment