Skip to content
This repository has been archived by the owner on Jul 14, 2023. It is now read-only.

Commit

Permalink
Merge pull request #3 from mathewmeconry/feature/private-IP
Browse files Browse the repository at this point in the history
private ip in templates / different ways for host clean
  • Loading branch information
mathewmeconry authored Aug 14, 2018
2 parents 8abfea8 + 6f49483 commit 1b313af
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 40 deletions.
42 changes: 31 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,27 @@ Run install.sh script
- command to reload Icinga2 configs

## Usage
AWS for Icinga 2

optional arguments:
-h, --help show this help message and exit
-t TAGS [TAGS ...], --tags TAGS [TAGS ...]
Tag Filter: Key value pair
-th TEMPLATEHOST, --template-host TEMPLATEHOST
Which Template should be used for the host
-tc TEMPLATECHECK, --template-check TEMPLATECHECK
Which Template should be used for the checks
usage: icinga2-aws.py [-h] -t TAGS [TAGS ...] -th TEMPLATEHOST -tc
TEMPLATECHECK [-nc]
{clean} ...

AWS for Icinga 2

optional arguments:
-h, --help show this help message and exit
-t TAGS [TAGS ...], --tags TAGS [TAGS ...]
Tag Filter: Key value pair
-th TEMPLATEHOST, --template-host TEMPLATEHOST
Which Template should be used for the host
-tc TEMPLATECHECK, --template-check TEMPLATECHECK
Which Template should be used for the checks
-nc, --no-clean Don't clean host folders

subcommands:
valid subcommands

{clean} additional help
clean clean help

## Tag Parameter
The Tags are in following format:
Expand All @@ -36,9 +47,18 @@ Just use the same command
## Templates
For templates are following parameters available:
{HOST} = instance id
{IP} = instance public ip
{IP} or {PublicIP} = instance public ip
{PrivateIP} = instance private ip

If you need more just create a feature request

## noClean clean
sample usage of the --no-clean and clean feature
1. Create config for application:application1 with --no-clean
2. Create another config for application:application2 with --no-clean
**if on step 2 a clean function would be called, all instances from step 1 would be deleted**
3. call the clean command with another tag like icinga:true

## Contributing
1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
Expand Down
102 changes: 73 additions & 29 deletions icinga2-aws.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,25 @@
import shutil
import subprocess
import configparser
import sys

def writeTemplate(template, targetFile, targetFolder):
def writeTemplate(template, targetFile, targetFolder, instance):
with open(icinga2ConfigDir + 'conf.d/hosts/' + targetFolder + '/' + targetFile + '.conf', 'w') as out:
template = template
template = template.replace('{HOST}', instance.id)
template = template.replace('{IP}', instance.public_ip_address)
template = template.replace('{PrivateIP}', instance.private_ip_address)

if instance.public_ip_address:
template = template.replace(
'{PublicIP}', instance.public_ip_address)
# Backwards compatibility
template = template.replace('{IP}', instance.public_ip_address)
out.write(template)
out.flush()

out.close()


def walklevel(some_dir, level=1):
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
Expand All @@ -25,55 +33,91 @@ def walklevel(some_dir, level=1):
if num_sep + level <= num_sep_this:
del dirs[:]


def cleanupHosts(instances):
for x in walklevel(icinga2ConfigDir + "conf.d/hosts/"):
instanceActive = False
if (x[0].find('i-') > -1):
folder_instance_id = x[0].split("/")[-1]
for instance in instances:
if x[0].split("/")[-1] == instance.id:
if folder_instance_id == instance.id:
instanceActive = True

if instanceActive == False:
shutil.rmtree(x[0])
for directory in os.listdir(config['Default']['php4nagiosPerfDataFolder']):
if(directory.find(instance.id) > -1):
if(directory.find(folder_instance_id) > -1):
if os.path.exists(config['Default']['php4nagiosPerfDataFolder'] + directory):
shutil.rmtree(config['Default']['php4nagiosPerfDataFolder'] + instance.id)
shutil.rmtree(
config['Default']['php4nagiosPerfDataFolder'] + folder_instance_id)

def get_instances(tags):
filters = []
filters.append({"Name": 'instance-state-name', "Values": ['running']})
for tag in tags:
tag = tag.split(':')
filters.append({"Name": "tag:" + tag[0], "Values": [tag[1]]})

ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(
Filters=filters)

return instances

def create_configs(instances, templateHost, templateCheck, noClean):
for instance in instances:
if not os.path.exists(icinga2ConfigDir + "conf.d/hosts/" + instance.id):
os.makedirs(icinga2ConfigDir + "conf.d/hosts/" + instance.id)
writeTemplate(templateHost, instance.id, instance.id, instance)
writeTemplate(templateCheck, 'checks', instance.id, instance)

if noClean == False or noClean == None:
cleanupHosts(instances)

def __add_main_parser(parser):
parser.add_argument('-t', '--tags', nargs='+', required=True,
help='Tag Filter: Key value pair')
parser.add_argument('-th', '--template-host', dest='templateHost', type=open,
required=True, help='Which Template should be used for the host')
parser.add_argument('-tc', '--template-check', dest='templateCheck', type=open,
required=True, help='Which Template should be used for the checks')
parser.add_argument('-nc', '--no-clean', dest='noClean',
default=False, action='store_true', required=False, help='Don\'t clean host folders')

def __add_clean_parser(parser):
subparsers = parser.add_subparsers(
title='subcommands', description='valid subcommands', help='additional help', dest="command")

parser_clean = subparsers.add_parser('clean', help='clean help')
parser_clean.add_argument('-t', '--tags', nargs='+',
required=True, help='Tag Filter: Key value pair')

config = configparser.ConfigParser()
config.read('config.ini')

icinga2ConfigDir = config['Default']['icinga2ConfigDir']

parser = argparse.ArgumentParser(description='AWS for Icinga 2')
parser.add_argument('-t', '--tags', nargs='+', required=True, help='Tag Filter: Key value pair')
parser.add_argument('-th', '--template-host', dest='templateHost', type=open, required=True, help='Which Template should be used for the host')
parser.add_argument('-tc', '--template-check', dest='templateCheck', type=open, required=True, help='Which Template should be used for the checks')

# little hack to show the correct help and the really required params
if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help']:
__add_main_parser(parser)
__add_clean_parser(parser)
elif len(sys.argv) > 1 and sys.argv[1] == 'clean':
__add_clean_parser(parser)
else:
__add_main_parser(parser)

args = parser.parse_args()

filters = []
filters.append({"Name": 'instance-state-name', "Values": ['running']})
for tag in args.tags:
tag = tag.split(':')
filters.append({"Name": "tag:"+tag[0], "Values": [tag[1]]})
instances = get_instances(args.tags)

if hasattr(args, 'command') and args.command == 'clean':
cleanupHosts(instances)
else:
templateHost = args.templateHost.read()
templateCheck = args.templateCheck.read()
create_configs(instances, templateHost, templateCheck, args.noClean)

ec2 = boto3.resource('ec2')
templateHost = args.templateHost.read()
templateCheck = args.templateCheck.read()

instances = ec2.instances.filter(
Filters=filters)

for instance in instances:
if not os.path.exists(icinga2ConfigDir + "conf.d/hosts/" + instance.id):
os.makedirs(icinga2ConfigDir + "conf.d/hosts/" + instance.id)
writeTemplate(templateHost, instance.id, instance.id)
writeTemplate(templateCheck, 'checks', instance.id)

cleanupHosts(instances)

subprocess.call(config['Default']['icinga2ReloadCommand'], shell=True)

0 comments on commit 1b313af

Please sign in to comment.