def resolve_file(filename, basefile):
    if filename[0] == "/":
        return existing(filename)
    if re.match(r"^(\.\./\.\./|\.\./|\./)?aws-utils/.*", filename):
        return existing(find_include(re.sub(r"^(\.\./\.\./|\.\./|\./)?aws-utils/", "", filename)))
    if re.match(r"^\(\(\s?includes\s?\)\)/.*", filename):
        return existing(find_include(re.sub(r"^\(\(\s?includes\s?\)\)/", "", filename)))
    base = os.path.dirname(basefile)
    if len(base) == 0:
        base = "."
    return existing(base + "/" + filename)
Example #2
0
 def write(self, yes=False):
     if "Files" in self.template:
         for entry in self.template["Files"]:
             for source, dest in list(entry.items()):
                 dest = self.component_name + os.sep + dest % self.__dict__
                 dest = os.path.normpath(dest)
                 dest_dir = os.path.normpath(os.path.dirname(dest))
                 if not os.path.exists(dest_dir):
                     os.makedirs(dest_dir)
                 source_file = find_include(source)
                 shutil.copy2(source_file, dest)
         self.template.pop("Files", None)
     stack_dir = os.path.join(".", self.component_name,
                              "stack-" + self.stack_name)
     if not os.path.exists(stack_dir):
         os.makedirs(stack_dir)
     if self.branch_mode == BRANCH_MODES.SINGLE_STACK:
         file_name = "infra.properties"
         stack_props = os.path.join(stack_dir, file_name)
         if not os.path.exists(stack_props):
             with open(stack_props, 'w') as stack_props_file:
                 stack_props_file.write("STACK_NAME=$ORIG_STACK_NAME\n")
     stack_template = os.path.join(stack_dir, "template.yaml")
     if os.path.exists(stack_template) and not yes:
         answer = eval(
             input("Overwrite " + self.stack_name + " stack? (n): "))
         if not answer or not answer.lower() == "y":
             return False
     with open(stack_template, "w") as stack_file:
         stack_file.write(yaml_save(self.template))
     return True
Example #3
0
def resolve_include():
    """Find a file from the first of the defined include paths
    """
    parser = get_parser()
    parser.add_argument("file", help="The file to find")
    argcomplete.autocomplete(parser)
    args = parser.parse_args()
    inc_file = find_include(args.file)
    if not inc_file:
        parser.error("Include " + args.file + " not found on include paths " +
                     str(include_dirs))
    print(inc_file)
Example #4
0
def disk_by_drive_letter(drive_letter):
    ret = {}
    proc = Popen([
        "powershell.exe",
        find_include("disk-by-drive-letter.ps1"),
        drive_letter.upper() + ":"
    ],
                 stdout=PIPE,
                 stderr=PIPE)
    output = proc.communicate()[0]
    tree = ET.fromstring(output)
    for obj in tree.iter("Object"):
        for prop in obj.iter("Property"):
            try:
                ret[prop.attrib['Name']] = int(prop.findtext("."))
            except ValueError:
                ret[prop.attrib['Name']] = prop.findtext(".")
            except TypeError:
                continue
    return ret
def create_account(email,
                   account_name,
                   role_name="OrganizationAccountAccessRole",
                   trust_role="TrustedAccountAccessRole",
                   access_to_billing=True,
                   trusted_accounts=None,
                   mfa_token=None):
    if access_to_billing:
        access = "ALLOW"
    else:
        access = "DENY"
    timeout = 300

    if trusted_accounts:
        trusted_roles = {}
        for trusted_account in trusted_accounts:
            role_arn = find_role_arn(trusted_account)
            if not role_arn:
                raise Exception("Failed to resolve trusted account " +
                                trusted_account)
            trusted_roles[trusted_account] = role_arn

    response = organizations().create_account(Email=email,
                                              AccountName=account_name,
                                              RoleName=role_name,
                                              IamUserAccessToBilling=access)
    if 'CreateAccountStatus' in response and 'Id' in response[
            'CreateAccountStatus']:
        create_account_id = response['CreateAccountStatus']['Id']
        startTime = time()
        status = response['CreateAccountStatus']['State']
        while time() - startTime < timeout and not status == "SUCCEEDED":
            if response['CreateAccountStatus']['State'] == "FAILED":
                raise Exception(
                    "Account creation failed: " +
                    response['CreateAccountStatus']['FailureReason'])
            print("Waiting for account creation to finish")
            sleep(2)
            response = organizations().describe_create_account_status(
                CreateAccountRequestId=create_account_id)
            status = response['CreateAccountStatus']['State']
        if time() - startTime > timeout and not status == "SUCCEEDED":
            raise Exception("Timed out waiting to create account " +
                            response['CreateAccountStatus']['State'])
        account_id = response['CreateAccountStatus']['AccountId']

    os.environ['paramManagedAccount'] = account_id
    os.environ['paramManageRole'] = role_name
    template = find_include("manage-account.yaml")
    cf_deploy.deploy("managed-account-" + account_name, template, region())

    if trusted_accounts:
        role_arn = "arn:aws:iam::" + account_id + ":role/" + role_name
        assumed_creds = utils.assume_role(role_arn, mfa_token_name=mfa_token)
        sess = session(aws_access_key_id=assumed_creds['AccessKeyId'],
                       aws_secret_access_key=assumed_creds['SecretAccessKey'],
                       aws_session_token=assumed_creds['SessionToken'])
        for trusted_account in trusted_accounts:
            os.environ['paramTrustedAccount'] = trusted_roles[
                trusted_account].split(":")[4]
            os.environ['paramRoleName'] = trust_role
            template = find_include("trust-account-role.yaml")
            cf_deploy.deploy("trust-" + trusted_account,
                             template,
                             utils.region(),
                             session=sess)
        template = find_include("manage-account.yaml")
        for trusted_account in trusted_accounts:
            role_arn = trusted_roles[trusted_account]
            print("Assuming role " + role_arn)
            assumed_creds = utils.assume_role(role_arn,
                                              mfa_token_name=mfa_token)
            sess = session(
                aws_access_key_id=assumed_creds['AccessKeyId'],
                aws_secret_access_key=assumed_creds['SecretAccessKey'],
                aws_session_token=assumed_creds['SessionToken'])
            os.environ['paramManagedAccount'] = account_id
            os.environ['paramRoleName'] = trust_role
            cf_deploy.deploy("managed-account-" + account_name + "-" +
                             account_id,
                             template,
                             region(),
                             session=sess)
Example #6
0
 def set_template(self, template):
     common_yaml = yaml_load(
         open(find_include("creatable-templates/network/common.yaml")))
     self.template, self.common_yaml = \
         _get_network_yaml(self.stack_name, self.vpc_cidr, self.subnet_prefixlen,
                           self.subnet_base, template, common_yaml)
Example #7
0
def load_template(template):
    file_name = find_include("creatable-templates/" + template + ".yaml")
    if file_name:
        return yaml_load(open(file_name))
    else:
        return None