예제 #1
0
파일: setup.py 프로젝트: Miradot/demojam
def write_group_vars(settings):

    vault_secret = open("ansible/.vault_pass.txt", "r").read().rstrip("\n")
    vault = Vault(vault_secret)

    secret_keywords = [
        "user", "pass", "access_key", "secret_key", "token", "ansible_user",
        "ansible_become_pass"
    ]

    for k, v in settings.items():
        secrets = dict()
        options = dict()
        for i in v:
            if i in secret_keywords:
                secrets[i] = v[i]
            else:
                if i != "host":
                    options[i] = v[i]

        vault.dump(secrets,
                   open("ansible/group_vars/{}/vault.yml".format(k), "wb"))

        if options:
            with open("ansible/group_vars/{}/options.yml".format(k),
                      "w") as infile:
                yaml.dump(options, infile)
예제 #2
0
    def callback(self, args):
        file_prefix = os.path.splitext(args.private_key_file)[0]
        args.vault_password_file = args.vault_password_file or \
            "{}.vault_password".format(file_prefix)
        if os.path.exists(args.vault_password_file):
            with open(args.vault_password_file, "r") as f:
                vault_password = f.read().strip()

            if vault_password is None:
                raise YBOpsRuntimeError("Unable to read {}".format(
                    args.vault_password_file))
        else:
            raise YBOpsRuntimeError("Vault password file doesn't exists.")

        if args.vault_file is None:
            args.vault_file = "{}.vault".format(file_prefix)

        vault = Vault(vault_password)
        data = vault.load(open(args.vault_file).read())

        if args.has_sudo_password:
            if not YB_SUDO_PASS:
                raise YBOpsRuntimeError("Did not find sudo password.")
            data['ansible_become_pass'] = YB_SUDO_PASS

        vault.dump(data, open(args.vault_file, 'w'))
        print(
            json.dumps({
                "vault_file": args.vault_file,
                "vault_password": args.vault_password_file
            }))
예제 #3
0
 def _set_secret(self, var, value):
 # No effort is made to preserve the original YAML format (comments, etc.),
 # and no edge cases are handled (e.g. vault does not exist, etc.)
     data = self._get_vault_variables() or {}
     data[var] = value
     vault = Vault(self._get_ansible_vault_password())
     with open(self.vault_file_path, 'wb') as vf:
         vault.dump(data, vf)
     self._get_vault_variables.reset_cache(self)
예제 #4
0
    def callback(self, args):
        file_prefix = os.path.splitext(args.private_key_file)[0]

        try:
            if args.vault_password_file is None:
                vault_password = generate_random_password()
                args.vault_password_file = "{}.vault_password".format(
                    file_prefix)
                with open(args.vault_password_file, "w") as f:
                    f.write(vault_password)
            elif os.path.exists(args.vault_password_file):
                with open(args.vault_password_file, "r") as f:
                    vault_password = f.read().strip()

                if vault_password is None:
                    raise YBOpsRuntimeError("Unable to read {}".format(
                        args.vault_password_file))
            else:
                raise YBOpsRuntimeError("Vault password file doesn't exist.")

            if args.vault_file is None:
                args.vault_file = "{}.vault".format(file_prefix)

            rsa_key = validated_key_file(args.private_key_file)
        except Exception:
            self._cleanup_dir(os.path.dirname(args.private_key_file))
            raise

        # TODO: validate if the file provided is actually a private key file or not.
        public_key = format_rsa_key(rsa_key, public_key=True)
        private_key = format_rsa_key(rsa_key, public_key=False)
        self.cluster_vault.update(id_rsa=private_key,
                                  id_rsa_pub=public_key,
                                  authorized_keys=public_key)

        # These are saved for itest specific improvements.
        aws_access_key = os.environ.get('AWS_ACCESS_KEY_ID', "")
        aws_secret = os.environ.get('AWS_SECRET_ACCESS_KEY', "")
        if aws_access_key and aws_secret:
            self.cluster_vault.update(
                AWS_ACCESS_KEY_ID=os.environ['AWS_ACCESS_KEY_ID'],
                AWS_SECRET_ACCESS_KEY=os.environ['AWS_SECRET_ACCESS_KEY'])

        vault_data = dict(cluster_server_vault=self.cluster_vault)
        if args.has_sudo_password:
            sudo_password = getpass.getpass("SUDO Password: "******"ansible_become_pass": sudo_password})

        vault = Vault(vault_password)
        vault.dump(vault_data, open(args.vault_file, 'w'))
        print(
            json.dumps({
                "vault_file": args.vault_file,
                "vault_password": args.vault_password_file
            }))
예제 #5
0
def main():
    home = expanduser("~")
    failed = False
    fields = {
        "file": {
            "required": True,
            "type": "str"
        },
        "region": {
            "required": True,
            "type": "str"
        },
        "roles": {
            "required": True,
            "type": "list"
        },
    }

    module = AnsibleModule(argument_spec=fields)
    try:
        file = open(home + "/" + module.params['file'], "r")
        access_key = file.readline().rstrip('\n')
        secret_key = file.readline().rstrip('\n')
        file.close()
        file = open(home + "/" + "passwd/ansible-passwd", "r")

        data = {
            "region": module.params['region'],
            "access_key": access_key,
            "secret_key": secret_key
        }

        vault = Vault(file.readline().rstrip('\n'))

        awsconffile = open(home + "/" + ".aws/credentials", "w")
        awsconffile.write('[default]\n')
        awsconffile.write('aws_access_key_id = ' + access_key + '\n')
        awsconffile.write('aws_secret_access_key= ' + secret_key + '\n')
        awsconffile.close()

        awsconffile = open(home + "/" + ".aws/config", "w")
        awsconffile.write('[default]\n')
        awsconffile.write('region = ' + module.params['region'] + '\n')
        awsconffile.close()

        for role in module.params['roles']:
            vault.dump(data, open("./roles/" + role + "/vars/vault.yml", "w"))

        response = "Done"

    except:
        response = "Error"
        failed = True

    module.exit_json(changed=False, meta=response, failed=failed)
예제 #6
0
def encrypt_file(path, password_file, newpath=None, secrets=None):
    '''Encrypts an Ansible Vault YAML file. Returns encrypted data. Set newpath to
        write the result somewhere. Set secrets to specify inline secret addresses.'''
    log.debug('Reading decrypted data from {}...'.format(path))
    data = parse_yaml(path)
    if not data:
        raise ValueError('The YAML file "{}" could not be parsed'.format(path))
    else:
        log.debug('Got vars: {}'.format(data))

    with open(password_file) as f:
        p = f.read().strip()
        log.debug('Read pass from {}: {}'.format(password_file, p))

    if secrets:
        # newdata = data.copy()
        secrets = list(secrets)
        log.debug('Received {} secrets: {}'.format(len(secrets), secrets))
        for address in secrets:
            plaintext = get_dict_value(data, address)
            log.debug('Re-encrypting "{}" at {} with new password...'.format(
                plaintext, address))
            put_dict_value(
                data, address,
                VaultString.encrypt(plaintext=plaintext, password=p))
        if newpath:
            log.debug('Writing {} to {}...'.format(data, newpath, p))
            write_yaml(newpath, data)
        return data
    else:
        vault = Vault(p)
        encrypted = vault.dump(data)
        with open(newpath, 'w') as f:
            f.write(encrypted)
        return encrypted
예제 #7
0
파일: vault.py 프로젝트: gocreating/lation
class Vault():
    @staticmethod
    def to_encrypted_name(name):
        return f'{name}.encrypted'

    @staticmethod
    def to_decrypted_name(name):
        return '.'.join(name.split('.')[:-1])

    def __init__(self, password):
        self.ansible_vault = AnsibleVault(password)
        self.fs = FileSystem()

    def encrypt(self, src, dest=None):
        srcs = self.fs.deserialize_name(src)
        assert self.fs.is_file(srcs), 'src should be a file'
        if not dest:
            dests = srcs.copy()
            dests[-1] = Vault.to_encrypted_name(srcs[-1])
            dest = self.fs.serialize_name(dests)
        with open(src, 'r') as input_file:
            raw_data = input_file.read()
        with open(dest, 'wb') as output_file:
            self.ansible_vault.dump(raw_data, output_file)

    def decrypt(self, src, dest=None):
        srcs = self.fs.deserialize_name(src)
        assert self.fs.is_file(srcs), 'src should be a file'
        if not dest:
            dests = srcs.copy()
            dests[-1] = Vault.to_decrypted_name(srcs[-1])
            dest = self.fs.serialize_name(dests)
        with open(src, 'r') as input_file:
            encrypted_data = input_file.read()
            try:
                decrypted_data = self.ansible_vault.load(encrypted_data)
            except AnsibleVaultError as e:
                raise Exception('Decrypt failed')
        with open(dest, 'w') as output_file:
            output_file.write(decrypted_data)
예제 #8
0
    def callback(self, args):
        file_prefix = os.path.splitext(args.private_key_file)[0]
        if args.vault_password is None:
            vault_password = generate_random_password()
            args.vault_password = "******".format(file_prefix)
            with file(args.vault_password, "w") as f:
                f.write(vault_password)
        elif os.path.exists(args.vault_password):
            with file(args.vault_password) as f:
                vault_password = f.read().strip()

            if vault_password is None:
                raise YBOpsRuntimeError("Unable to read {}".format(
                    args.vault_password))
        else:
            raise YBOpsRuntimeError("Vault password file doesn't exists.")

        if args.vault_file is None:
            args.vault_file = "{}.vault".format(file_prefix)

        rsa_key = validated_key_file(args.private_key_file)
        # TODO: validate if the file provided is actually a private key file or not.
        public_key = format_rsa_key(rsa_key, public_key=True)
        private_key = format_rsa_key(rsa_key, public_key=False)
        self.cluster_vault.update(id_rsa=private_key,
                                  id_rsa_pub=public_key,
                                  authorized_keys=public_key)
        vault_data = dict(cluster_server_vault=self.cluster_vault)
        if args.has_sudo_password:
            sudo_password = getpass.getpass("SUDO Password: "******"ansible_become_pass": sudo_password})

        vault = Vault(vault_password)
        vault.dump(vault_data, open(args.vault_file, 'w'))
        print json.dumps({
            "vault_file": args.vault_file,
            "vault_password": args.vault_password
        })
예제 #9
0
def create_pool():
    pooltype = request.form['pooltype']
    poolname = request.form['poolname'].upper()
    if pooltype == 'vmware':
        vcname = request.form['vcname']
        vcuser = request.form['vcuser']
        vcpass = request.form['vcpass']
        clustername = request.form['clustername']
        networkname = request.form.get('networkname', None)
        datastorename = request.form.get('datastorename', None)
        datacentername = request.form.get('datacentername', None)

        dbsession = db.get_session()
        dbsession = db.get_session()
        pooltable = db.get_pooltbl()
        privatepool = db.get_privatepooltbl()
        poolid = str(uuid.uuid4()) 
        passwd = passgen()
        #from Crypto.Cipher import AES
        import base64
        ## Encryption
        #encryption_suite = AES.new('BM^@Y5BENeX2qpw$rRRkfR1LQ5$jQtMf', AES.MODE_CBC, 'This is an IV456')
        #passwd = encryption_suite.encrypt(passwd)
        hashpass = base64.b64encode(passwd)

	from ansible_vault import Vault
	vault = Vault(passwd)
	vault_content = vault.dump({'poolpass' : str(vcpass)})
        hashcontent = base64.b64encode(vault_content)

        try:
            sys.path.append(ductrix_root)
            dbsession.add(pooltable( poolname=poolname, pooltype=pooltype, poolid=poolid))
            dbsession.add(privatepool(username=vcuser,password=hashpass, content=hashcontent, targetserver=vcname, 
		clusternm=clustername, poolid=poolid, networknm=networkname, storagenm=datastorename, datacenternm=datacentername))
            dbsession.commit()
            dbsession.close()

            successmsg = "{0} Pool has been created sucessfully".format(poolname)
            job_msg = gen_message("success", successmsg)

        except Exception as inst: 
            error = inst
            errormsg = "Error occured while connecting to {0} : {1} ".format(poolname, error)
            job_msg = gen_message("danger", errormsg)
        return redirect(url_for('pools', message=job_msg))
예제 #10
0
def saveVaultFile(file, data):
    vault = Vault(vaultpwd)
    vault.dump(data, open(vaultFile, 'w'))
예제 #11
0
파일: t.py 프로젝트: infra-ops/cloud-ops
from ansible_vault import Vault
#from CorrectPythonPackage.token import *


vault = Vault('tower@123')
data = vault.dump(vault, open('vault.yml', 'w'))

# also you can get encrypted text
print(vault.dump(data))


예제 #12
0
class AnsibleVaultService:
    def __init__(self, password: str):
        self.__vault = Vault(password)

    def encrypt(self, data: str):
        return self.__vault.dump(data)
예제 #13
0
def saveVaultFile(file, data):
    vault = Vault(vaultpwd)
    vault.dump(data, open(vaultFile, 'w'))