Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def attach(args):
if args.instance is None:
args.instance = get_metadata("instance-id")
devices = args.device if args.device else ["xvd" + chr(i + 1) for i in reversed(range(ord("a"), ord("z")))]
for i, device in enumerate(devices):
try:
args.device = devices[i]
res = attach_volume(args)
break
except ClientError as e:
if re.search("VolumeInUse.+already attached to an instance", str(e)):
if resources.ec2.Volume(args.volume_id).attachments[0]["InstanceId"] == args.instance:
logger.warn("Volume %s is already attached to instance %s", args.volume_id, args.instance)
break
if i + 1 < len(devices) and re.search("InvalidParameterValue.+Attachment point.+is already in use", str(e)):
logger.warn("BDM node %s is already in use, looking for next available node", devices[i])
continue
raise
res = clients.ec2.get_waiter("volume_in_use").wait(VolumeIds=[args.volume_id])
if args.format or args.mount:
for i in range(30):
try:
find_devnode(args.volume_id)
break
except Exception:
logger.debug("Waiting for device node to appear for %s", args.volume_id)
time.sleep(1)
if args.format:
DryRun=not args.force)
elif name.startswith("fs-"):
efs = clients.efs
for mount_target in efs.describe_mount_targets(FileSystemId=name)["MountTargets"]:
if args.force:
efs.delete_mount_target(MountTargetId=mount_target["MountTargetId"])
try:
while efs.describe_mount_targets(MountTargetId=mount_target["MountTargetId"]):
time.sleep(1)
except ClientError as e:
expect_error_codes(e, "MountTargetNotFound")
efs.delete_file_system(FileSystemId=name) if args.force else True
elif name.startswith("AKIA") and len(name) == 20 and name.upper() == name:
clients.iam.delete_access_key(AccessKeyId=name) if args.force else True
elif name.startswith("AROA") and len(name) == 21 and name.upper() == name:
for role in resources.iam.roles.all():
if role.role_id == name:
logger.info("Deleting %s", role)
for instance_profile in role.instance_profiles.all():
instance_profile.remove_role(RoleName=role.name) if args.force else True
instance_profile.delete() if args.force else True
for policy in role.attached_policies.all():
role.detach_policy(PolicyArn=policy.arn) if args.force else True
for policy in role.policies.all():
policy.delete() if args.force else True
role.delete() if args.force else True
break
else:
raise Exception("Role {} not found".format(name))
else:
raise Exception("Name {} not recognized as an AWS resource".format(name))
except ClientError as e:
def put_alarm(args):
sns = resources.sns
logs = clients.logs
cloudwatch = clients.cloudwatch
topic = sns.create_topic(Name=args.alarm_name)
topic.subscribe(Protocol="email", Endpoint=args.email)
logs.put_metric_filter(logGroupName=args.log_group_name,
filterName=args.alarm_name,
filterPattern=args.pattern,
metricTransformations=[dict(metricName=args.alarm_name,
metricNamespace=__name__,
metricValue="1")])
cloudwatch.put_metric_alarm(AlarmName=args.alarm_name,
MetricName=args.alarm_name,
Namespace=__name__,
Statistic="Sum",
Period=300,
Threshold=1,
def account_password_policy(self):
if "account_password_policy" not in self.cache:
self.cache["account_password_policy"] = resources.iam.AccountPasswordPolicy()
return self.cache["account_password_policy"]
def users(args):
current_user = resources.iam.CurrentUser()
def mark_cur_user(cell, row):
return ">>>" if row.user_id == current_user.user_id else ""
def describe_mfa(cell, row):
try:
return "Enabled" if list(row.mfa_devices.all()) else "Disabled"
except botocore.exceptions.ClientError:
return "Unknown"
def describe_access_keys(cell):
return ", ".join([k.id + ": " + k.status for k in cell.all()])
users = list(resources.iam.users.all())
for user in users:
user.cur, user.mfa = "", ""
def rm(args):
for name in args.names:
try:
if args.key_pair:
resources.ec2.KeyPair(name).delete(DryRun=not args.force)
elif args.elb:
if args.force:
clients.elb.delete_load_balancer(LoadBalancerName=name)
else:
clients.elb.describe_load_balancer_attributes(LoadBalancerName=name)
elif getattr(args, "lambda"):
if args.force:
getattr(clients, "lambda").delete_function(FunctionName=name)
else:
getattr(clients, "lambda").get_function(FunctionName=name)
elif name.startswith("sg-"):
resources.ec2.SecurityGroup(name).delete(DryRun=not args.force)
elif name.startswith("vol-"):
resources.ec2.Volume(name).delete(DryRun=not args.force)
elif name.startswith("snap-"):
resources.ec2.Snapshot(name).delete(DryRun=not args.force)
def grant(args):
"""
Given an IAM role or instance name, attach an IAM policy granting
appropriate permissions to subscribe to deployments. Given a
GitHub repo URL, create and record deployment keys for the repo
and any of its private submodules, making the keys accessible to
the IAM role.
"""
try:
role = resources.iam.Role(args.iam_role_or_instance)
role.load()
except ClientError:
role = get_iam_role_for_instance(args.iam_role_or_instance)
role.attach_policy(PolicyArn=ensure_deploy_iam_policy().arn)
for private_repo in [args.repo] + list(private_submodules(args.repo)):
gh_owner_name, gh_repo_name = parse_repo_name(private_repo)
secret = secrets.put(argparse.Namespace(secret_name="deploy.{}.{}".format(gh_owner_name, gh_repo_name),
iam_role=role.name,
instance_profile=None,
iam_group=None,
iam_user=None,
generate_ssh_key=True))
get_repo(private_repo).create_key(__name__ + "." + role.name, secret["ssh_public_key"])
logger.info("Created deploy key %s for IAM role %s to access GitHub repo %s",
secret["ssh_key_fingerprint"], role.name, private_repo)
def ensure_alarm(self, name, pattern, log_group_name):
# See http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html
sns = resources.sns
logs = clients.logs
cloudwatch = clients.cloudwatch
topic = sns.create_topic(Name=name)
topic.subscribe(Protocol='email', Endpoint=self.email)
logs.put_metric_filter(logGroupName=log_group_name,
filterName=name,
filterPattern=pattern,
metricTransformations=[dict(metricName=name,
metricNamespace=__name__,
metricValue="1")])
cloudwatch.put_metric_alarm(AlarmName=name,
MetricName=name,
Namespace=__name__,
Statistic="Sum",
Period=300,
Threshold=1,
def column_completer(parser, **kwargs):
resource = getattr(resources, parser.get_default("resource"))
subresource = getattr(resource, parser.get_default("subresource"))
return [attr for attr in dir(subresource("")) if not attr.startswith("_")]