How to use the crhelper.CfnResource function in crhelper

To help you get started, we’ve selected a few crhelper examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mozilla / security / operations / cloudformation-templates / oidc_identity_provider / oidc_identity_provider.py View on Github external
import boto3
from crhelper import CfnResource
from botocore.exceptions import ClientError

helper = CfnResource(
    json_logging=False, log_level='INFO', boto_level='CRITICAL')

try:
    iam = boto3.client("iam")
    ARN_FORMAT = "arn:aws:iam::{}:oidc-provider/{}"
except Exception as e:
    helper.init_failure(e)


def get_comma_delimited_list(event, parameter):
    value = event['ResourceProperties'].get(parameter)
    return [x.strip() for x in value.split(',')] if value else []


def get_parameters(event):
    aws_account_id = event['StackId'].split(':')[4]
github aws-quickstart / quickstart-amazon-eks / functions / source / KubeManifest / lambda_function.py View on Github external
import json
import logging
import boto3
import subprocess
import shlex
import os
import re
from ruamel import yaml
from datetime import date, datetime
from crhelper import CfnResource
from time import sleep

logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG')

try:
    s3_client = boto3.client('s3')
    kms_client = boto3.client('kms')
except Exception as init_exception:
    helper.init_failure(init_exception)


def run_command(command):
    retries = 0
    while True:
        try:
            try:
                logger.debug("executing command: %s" % command)
                output = subprocess.check_output(shlex.split(command), stderr=subprocess.STDOUT).decode("utf-8")
                logger.debug(output)
github aws-quickstart / quickstart-amazon-eks / functions / source / KubeGet / lambda_function.py View on Github external
import json
import logging
import boto3
import subprocess
import shlex
import os
import time
from hashlib import md5
from crhelper import CfnResource

logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG')

try:
    s3_client = boto3.client('s3')
    kms_client = boto3.client('kms')
except Exception as init_exception:
    helper.init_failure(init_exception)


def run_command(command):
    try:
        print("executing command: %s" % command)
        output = subprocess.check_output(shlex.split(command), stderr=subprocess.STDOUT).decode("utf-8")
        print(output)
    except subprocess.CalledProcessError as exc:
        print("Command failed with exit code %s, stderr: %s" % (exc.returncode, exc.output.decode("utf-8")))
        raise Exception(exc.output.decode("utf-8"))
github aws-quickstart / quickstart-amazon-eks / functions / source / DeleteBucketContents / lambda_function.py View on Github external
#  Copyright 2016 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
#  This file is licensed to you under the AWS Customer Agreement (the "License").
#  You may not use this file except in compliance with the License.
#  A copy of the License is located at http://aws.amazon.com/agreement/ .
#  This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.
#  See the License for the specific language governing permissions and limitations under the License.

import boto3
import logging
from crhelper import CfnResource

logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG')


@helper.delete
def create_handler(event, context):
    s3 = boto3.client('s3')
    # Delete KeyBucket contents
    if "KeyBucket" in event["ResourceProperties"].keys():
        logger.info('Getting KeyBucket objects...')
        s3objects = s3.list_objects_v2(Bucket=event["ResourceProperties"]["KeyBucket"])
        if 'Contents' in s3objects.keys():
            logger.info('Deleting KeyBucket objects %s...' % str(
                [{'Key': key['Key']} for key in s3objects['Contents']]))
            s3.delete_objects(Bucket=event["ResourceProperties"]["KeyBucket"],
                              Delete={'Objects': [{'Key': key['Key']} for key in s3objects['Contents']]})
        # Delete Output bucket contents and versions
    if "OutputBucket" in event["ResourceProperties"].keys():
github aws-quickstart / quickstart-cloud9-ide / functions / source / c9DiskResize / lambda_function.py View on Github external
from __future__ import print_function
import logging
from time import sleep
import boto3
from crhelper import CfnResource

logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG', boto_level='CRITICAL')

try:
    ssm_client = boto3.client('ssm')
    ec2_client = boto3.client('ec2')
except Exception as e:
    helper.init_failure(e)


def get_command_output(instance_id, command_id):
    response = ssm_client.get_command_invocation(CommandId=command_id, InstanceId=instance_id)
    if response['Status'] in ['Pending', 'InProgress', 'Delayed', 'Delivery Timed Out', 'Execution Timed Out', 'Failed', 'Canceled', 'Undeliverable', 'Terminated']:
        return
    return response


def send_command(instance_id, commands):
github aws-quickstart / quickstart-amazon-eks / functions / source / KubeConfigUpload / lambda_function.py View on Github external
kind: Config
preferences: {{}}
users:
- name: aws
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      command: aws-iam-authenticator
      args:
        - "token"
        - "-i"
        - "{cluster_name}"
"""


helper = CfnResource(json_logging=True, log_level='DEBUG')

try:
    kms_client = boto3.client('kms')
    s3_client = boto3.client('s3')
except Exception as init_exception:
    helper.init_failure(init_exception)


def create_kubeconfig(endpoint, cluster_name, ca_data):
    return KUBECONFIG.format(endpoint=endpoint, ca_data=ca_data, cluster_name=cluster_name)


@helper.create
@helper.update
def create_update_handler(event, _):
    os.environ["PATH"] = "/var/task/bin:" + os.environ.get("PATH")
github aws-quickstart / quickstart-amazon-eks / functions / source / Helm / lambda_function.py View on Github external
import json
import boto3
import subprocess
import shlex
import os
import random
import re
from crhelper import CfnResource
import logging
import string
from time import sleep
from datetime import datetime


logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG')

try:
    s3_client = boto3.client('s3')
    kms_client = boto3.client('kms')
except Exception as e:
    helper.init_failure(e)


def rand_string(l):
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(l))


def run_command(command):
    logger.debug("executing command: %s" % command)
    err = None
    output = None
github aws-quickstart / quickstart-amazon-eks / functions / source / CleanupSecurityGroupDependencies / lambda_function.py View on Github external
#  Copyright 2016 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
#  This file is licensed to you under the AWS Customer Agreement (the "License").
#  You may not use this file except in compliance with the License.
#  A copy of the License is located at http://aws.amazon.com/agreement/ .
#  This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.
#  See the License for the specific language governing permissions and limitations under the License.

import logging
import boto3
from crhelper import CfnResource

logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG')


def delete_dependencies(sg_id, c):
    filters = [{'Name': 'ip-permission.group-id', 'Values': [sg_id]}]
    for sg in c.describe_security_groups(Filters=filters)['SecurityGroups']:
        for p in sg['IpPermissions']:
            if 'UserIdGroupPairs' in p.keys():
                if sg_id in [x['GroupId'] for x in p['UserIdGroupPairs']]:
                    try:
                        c.revoke_security_group_ingress(GroupId=sg['GroupId'], IpPermissions=[p])
                    except Exception as e:
                        logger.error("ERROR: %s %s" % (sg['GroupId'], str(e)))
    filters = [{'Name': 'egress.ip-permission.group-id', 'Values': [sg_id]}]
    for sg in c.describe_security_groups(Filters=filters)['SecurityGroups']:
        for p in sg['IpPermissionsEgress']:
            if 'UserIdGroupPairs' in p.keys():
github aws-quickstart / quickstart-amazon-eks / functions / source / GetCallerArn / lambda_function.py View on Github external
import logging
import json
from datetime import timedelta
from time import sleep
import boto3
from crhelper import CfnResource

logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG')

try:
    cfn_client = boto3.client('cloudformation')
    ct_client = boto3.client('cloudtrail')
except Exception as init_exception:
    helper.init_failure(init_exception)


def get_caller_arn(stack_id):
    stack_properties = cfn_client.describe_stacks(StackName=stack_id)['Stacks'][0]
    try:
        parent_id = [t for t in stack_properties['Tags'] if t['Key'] == 'ParentStackId'][0]['Value']
    except ValueError:
        return "NotFound"
    except IndexError:
        return "NotFound"
github aws-quickstart / quickstart-amazon-eks / functions / source / CfnStackAssumeRole / lambda_function.py View on Github external
import string
import logging
import threading
from botocore.vendored import requests
import json
from botocore.credentials import (
    AssumeRoleCredentialFetcher,
    CredentialResolver,
    DeferredRefreshableCredentials
)
from botocore.session import Session
from botocore.exceptions import ClientError
from crhelper import CfnResource

logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=True, log_level='DEBUG')

try:
    lambda_client = boto3.client("lambda")
    events_client = boto3.client("events")
except Exception as init_exception:
    helper.init_failure(init_exception)


cfn_states = {
    "failed": ["CREATE_FAILED", "ROLLBACK_IN_PROGRESS", "ROLLBACK_FAILED", "ROLLBACK_COMPLETE", "DELETE_FAILED",
               "UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_FAILED", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
               "UPDATE_ROLLBACK_COMPLETE"],
    "in_progress": ["CREATE_IN_PROGRESS", "DELETE_IN_PROGRESS", "UPDATE_IN_PROGRESS",
                    "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"],
    "success": ["CREATE_COMPLETE", "DELETE_COMPLETE", "UPDATE_COMPLETE"]
}

crhelper

crhelper simplifies authoring CloudFormation Custom Resources

Apache-2.0
Latest version published 2 years ago

Package Health Score

66 / 100
Full package analysis

Similar packages