remove_node.py 1.82 KB
Newer Older
Olav Morken's avatar
Olav Morken committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#!/usr/bin/env python3

import argparse
import contextlib
import json
import requests

import settings

@contextlib.contextmanager
def checked_http(text):
    print('{text}: '.format(text=text), end='')
    try:
        yield
        print('OK')
    except requests.exceptions.HTTPError as e:
        print('Failed: ', e.response.status_code, e.response.text)


def clean_node(node):
    headers = {
        "Accept": 'pson',
        "Content-Type": "text/pson",
    }
    cert = (settings.puppet_crt, settings.puppet_key)
    puppet_url = "https://{}:{}/puppet-ca/v1/certificate_status/{}?environment=ignored".format(settings.puppet_ca_host, settings.puppet_ca_port, node)
    with checked_http('Revoking certificate'):
        r = requests.put(puppet_url, cert=cert, verify=settings.puppet_ca, data='{"desired_state":"revoked"}', headers=headers)
        r.raise_for_status()

    with checked_http('Deleting certificate'):
        r = requests.delete(puppet_url, cert=cert, verify=settings.puppet_ca)
        r.raise_for_status()

    data = {
        'command': 'deactivate node',
        'version': 3,
        'payload': {
            'certname': node,
        },
    }
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
    }
    puppetdb_url = "https://{}:{}/pdb/cmd/v1".format(settings.puppetdb_host,
                                                     settings.puppetdb_port)

    with checked_http('Deleting from PuppetDB'):
50
        r = requests.post(puppetdb_url, cert=cert, verify=settings.puppet_ca, data=json.dumps(data), headers=headers)
Olav Morken's avatar
Olav Morken committed
51 52 53 54 55 56 57 58 59 60 61 62 63
        r.raise_for_status()


def main():
    parser = argparse.ArgumentParser(description='Delete puppet node')
    parser.add_argument('node', help='Node to delete')
    args = parser.parse_args()
    clean_node(args.node)


if __name__ == '__main__':
    main()