Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _get_state_file_from_s3(self, state_file_url, profile=None, region=None):
if profile:
session = boto3.session.Session(profile_name=profile, region_name=region)
else:
session = get_boto3_session()
s3 = session.resource('s3')
parts = state_file_url[5:].split('/')
bucket = parts[0]
filename = "/".join(parts[1:])
key = s3.Object(bucket, filename)
try:
state_file = key.get()["Body"].read().decode('utf-8')
except ClientError as ex:
if ex.response['Error']['Code'] == 'NoSuchKey':
raise NoSuchStateFile("Could not find Terraform state file {}".format(self.state_file_url))
else:
raise ex
return json.loads(state_file)
def create(ctx, service_name, update_configs, dry_run, wait, asg, force_asg):
"""
Create a new ECS service named SERVICE_NAME.
"""
service = FriendlyServiceFactory.new(service_name, config=ctx.obj['CONFIG'])
print()
if service.exists():
click.secho('Service "{}" already exists!'.format(service.serviceName), fg='red')
sys.exit(1)
click.secho('Creating service with these attributes:', fg='white')
click.secho(' Service info:', fg="green")
print_service_info(service)
click.secho(' Task Definition:', fg='green')
print_task_definition(service.desired_task_definition)
if service.tasks:
click.secho('\nCreating these helper tasks:', fg='white')
for key, value in service.tasks.items():
click.secho(" {}".format(key), fg='green')
print_task_definition(value.desired_task_definition)
parameters = service.get_config()
if update_configs:
interpolate=False,
use_aws_section=False
)
try:
section_yml = config.get_section_item(section, section_name)
except KeyError:
click.echo("Our container's deployfish config file '{}' does not have section '{}' in '{}'".format(
ctx.obj['CONFIG_FILE'] or 'deployfish.yml',
section_name,
section
))
sys.exit(1)
parameter_store = []
if 'config' in section_yml:
parameter_name = parameter_prefix + section_name
parameter_store = ParameterStore(parameter_name, cluster_name, yml=section_yml['config'])
parameter_store.populate()
if not dry_run:
for param in parameter_store:
if param.exists:
if param.should_exist:
os.environ[param.key] = param.aws_value
else:
print(
"event='deploy.entrypoint.parameter.ignored.not_in_deployfish_yml' section='{}' parameter='{}'".format(
section_name, param.name))
else:
print("event='deploy.entrypoint.parameter.ignored.not_in_aws' section='{}' parameter='{}'".format(
section_name, param.name))
else:
exists = []
notexists = []
@BaseParameter.name.setter
def name(self, name):
if not name:
raise ValueError('UnboundParameter.name cannot be empty.')
self._key = name.split('.')[-1]
prefix = '.'.join(name.split('.')[:-1])
self._prefix = '{}.'.format(prefix) if prefix else ''
self._from_aws()
return self.name > other.name
def __ge__(self, other):
return self.name >= other.name
def __le__(self, other):
return self.name <= other.name
def __eq__(self, other):
return self.name == other.name
def __ne__(self, other):
return self.name != other.name
class UnboundParameter(BaseParameter):
"""
This is a parameter not bound to an ECS service or task.
"""
@BaseParameter.prefix.setter
def prefix(self, value):
self._prefix = value
if self._prefix is None:
self._prefix = ''
self._from_aws()
@BaseParameter.name.setter
def name(self, name):
if not name:
raise ValueError('UnboundParameter.name cannot be empty.')
self._key = name.split('.')[-1]
def _get_state_file_from_s3(self, state_file_url, profile=None, region=None):
if profile:
session = boto3.session.Session(profile_name=profile, region_name=region)
else:
session = get_boto3_session()
s3 = session.resource('s3')
parts = state_file_url[5:].split('/')
bucket = parts[0]
filename = "/".join(parts[1:])
key = s3.Object(bucket, filename)
try:
state_file = key.get()["Body"].read().decode('utf-8')
except ClientError as ex:
if ex.response['Error']['Code'] == 'NoSuchKey':
raise NoSuchStateFile("Could not find Terraform state file {}".format(self.state_file_url))
else:
raise ex
return json.loads(state_file)
def wrapper(*args, **kwargs):
try:
args[0].obj['CONFIG'] = Config(
filename=args[0].obj['CONFIG_FILE'],
env_file=args[0].obj['ENV_FILE'],
import_env=args[0].obj['IMPORT_ENV'],
tfe_token=args[0].obj['TFE_TOKEN']
)
except NoSuchStateFile as e:
click.echo(str(e))
sys.exit(1)
else:
return func(*args, **kwargs)
return wrapper
def _entrypoint(ctx, section, section_name, cluster_name, parameter_prefix, command, dry_run):
if section_name and cluster_name:
# The only thing we need out of Config is the names of any config:
# section variables we might have. We don't need to do interpolation
# in the config: section, because we retrieve the values from Parameter
# Store, and we don't want to use any aws: section that might be in the
# deployfish.yml to configure our boto3 session because we want to defer
# to the IAM ECS Task Role.
config = Config(
filename=ctx.obj['CONFIG_FILE'],
interpolate=False,
use_aws_section=False
)
try:
section_yml = config.get_section_item(section, section_name)
except KeyError:
click.echo("Our container's deployfish config file '{}' does not have section '{}' in '{}'".format(
ctx.obj['CONFIG_FILE'] or 'deployfish.yml',
section_name,
section
))
sys.exit(1)
parameter_store = []
if 'config' in section_yml:
parameter_name = parameter_prefix + section_name
def wrapper(*args, **kwargs):
try:
args[0].obj['CONFIG'] = Config(
filename=args[0].obj['CONFIG_FILE'],
env_file=args[0].obj['ENV_FILE'],
import_env=args[0].obj['IMPORT_ENV'],
tfe_token=args[0].obj['TFE_TOKEN']
)
except NoSuchStateFile as e:
click.echo(str(e))
sys.exit(1)
else:
return func(*args, **kwargs)
return wrapper
print("")
print("Load Balancer")
elb = get_boto3_session().client('elb')
response = elb.describe_instance_health(LoadBalancerName=self.load_balancer['load_balancer_name'])
states = response['InstanceStates']
if len(states) < desired_count:
success = False
for state in states:
if state['State'] != "InService" or state['Description'] != "N/A":
success = False
print(state['InstanceId'], state['State'], state['Description'])
elif lbtype == 'alb':
for target_group in self.load_balancer:
print("")
print("Target Group: {}".format(target_group['target_group_arn']))
alb = get_boto3_session().client('elbv2')
response = alb.describe_target_health(TargetGroupArn=target_group['target_group_arn'])
if len(response['TargetHealthDescriptions']) < desired_count:
success = False
for desc in response['TargetHealthDescriptions']:
if desc['TargetHealth']['State'] != 'healthy':
success = False
print(
desc['Target']['Id'],
desc['TargetHealth']['State'],
desc['TargetHealth'].get('Description', '')
)
return success