def main():
    args = get_args()
    # from requests.auth import HTTPBasicAuth
    requests.packages.urllib3.disable_warnings()

    # create connection object to foreman and nodes object
    f = Foreman(args['apiurl'], (args['username'], args['password']))

    if args['which'] == 'list' and args['groups']:
        # list hostgroups within Foreman
        group_dict = {}
        hostgroups = f.index_hostgroups()
        print("\n{0:40}{1}".format("Hostgroup", "ID"))
        print("{0:40}{1}".format("---------", "--\n"))
        for hostgroup in hostgroups:
            group_dict[hostgroup[u'hostgroup']
                       [u'name']] = hostgroup[u'hostgroup'][u'id']
            print("{0:40}{1}".format(hostgroup[u'hostgroup'][u'name'],
                                     hostgroup[u'hostgroup'][u'id']))

    if args['which'] == 'add':
        # add specified host to specified hostgroup
        hostid = get_host_id(f, args['hostname'])
        groupname = args['hostgroup']
        if not is_number(groupname):
            groupid = get_groupid(f, groupname)
        try:
            f.update_hosts(id=hostid, host={'hostgroup_id': groupid})
            print("Host successfully added to %s hostgroup" % groupname)
        except ForemanException, e:
            sys.exit(str(e) + ', see error description above')
def hostgroups_summary(foreman, user, passwd):
    """
    Show a summary of the current used and unused profiles and machines

    :param foreman: URL to the foreman server
    :param user: username to login into Foreman
    :param passwd: Password to use when logging in
    """
    frm = Foreman(foreman, (user, passwd))
    hgdict = {}
    for hg in frm.index_hostgroups(per_page=900):
        hgdict[hg['hostgroup']['id']] = hg['hostgroup']['name']
    notused = dict(hgdict.iteritems())
    groups = []
    ## Available
    hosts = frm.index_hosts(per_page=1000)
    puts(green("Total Available hosts: ", True) + green(len(hosts)))
    puts(blue("Available hosts by hostgroup:", True))
    for next_host in hosts:
        gid = next_host['host']['hostgroup_id']
        if gid:
            groups.append((hgdict[gid], gid))
            gid in notused and notused.pop(gid)
        else:
            groups.append(('No group', 'None'))
    if COUNTER:
        groups_count = dict(Counter(groups)).items()
    else:
        dict([(item, groups.count(item))
              for item in sorted(set(groups))]).items()
    groups_count.sort()
    for group, count in groups_count:
        gname, gid = group
        if gname != 'No group':
            puts(blue("\t%s (id=%d) = %s" % (gname, gid, white(count))))
        else:
            puts(blue("\tNo group = %s" % white(count)))
    ## Unused
    puts(blue("Unused hostgroups:", True))
    for gid, name in notused.iteritems():
        puts(blue("\t%s (id=%s)" % (name, gid)))
import csv, time

# create log file
logfile = "log" + time.strftime("_%m_%d_%Y-%H_%M_%S") + ".csv"
with open(logfile, "w") as f:
    writer = csv.writer(f)
    writer.writerow(["hostname", "hostgroup"])

# create connection object to foreman and object for all nodes
username = raw_input("Enter username: "******"dbname='puppetdb' user='******' host='devitpuppet.tsi.lan' password='******'")
cur = conn.cursor()
cur.execute("""select h.name,hg.name from hosts h left join hostgroups hg on h.hostgroup_id=hg.id""")
rows = cur.fetchall()

# iterate through foreman nodes and add to necessary hostgroup
for node in nodes:
    nodename = node[u'host'][u'name']
    if node[u'host'][u'hostgroup_id'] == None:
        for row in rows:
            if row[0] == nodename and row[1] == None: