Exemple #1
0
    def test_get_account_alias_invalid_env(self):
        """
    Tests if get_account_alias raises exceptions when given invalid environments

    Returns:
      None

    Raises:
      AssertionError if any of the assert checks fail
    """
        # Create junk environment values by attaching numbers to non-ephemeral environments and not attaching numbers
        # to ephemeral environments
        for env, account_alias in EFConfig.ENV_ACCOUNT_MAP.items():
            if env not in EFConfig.EPHEMERAL_ENVS:
                env += '0'
            with self.assertRaises(ValueError) as exception:
                ef_utils.get_account_alias(env)
            self.assertTrue("unknown env" in exception.exception.message)

        # Hard coded junk values
        with self.assertRaises(ValueError) as exception:
            ef_utils.get_account_alias("non-existent-env")
        self.assertTrue("unknown env" in exception.exception.message)
        with patch('ef_utils.env_valid') as mock_env_valid:
            with self.assertRaises(ValueError) as exception:
                mock_env_valid.return_value = True
                ef_utils.get_account_alias("non-existent-env")
        self.assertTrue(
            "has no entry in ENV_ACCOUNT_MAP" in exception.exception.message)
        with self.assertRaises(ValueError) as exception:
            ef_utils.get_account_alias("")
        self.assertTrue("unknown env" in exception.exception.message)
        with self.assertRaises(ValueError) as exception:
            ef_utils.get_account_alias(None)
        self.assertTrue("unknown env" in exception.exception.message)
Exemple #2
0
 def test_fully_qualified_env(self):
     """Does {{ENV_FULL}} resolve correctly"""
     # proto0
     test_string = "{{ENV_FULL}}"
     resolver = EFTemplateResolver(profile=get_account_alias("proto0"),
                                   env="proto0",
                                   region=TEST_REGION,
                                   service=TEST_SERVICE)
     resolver.load(test_string, PARAMS)
     self.assertEqual(resolver.render(), "proto0")
     # prod
     resolver = EFTemplateResolver(profile=get_account_alias("prod"),
                                   env="prod",
                                   region=TEST_REGION,
                                   service=TEST_SERVICE)
     resolver.load(test_string, PARAMS)
     self.assertEqual(resolver.render(), "prod")
     # mgmt.ellationeng
     resolver = EFTemplateResolver(
         profile=get_account_alias("mgmt.ellationeng"),
         env="mgmt.ellationeng",
         region=TEST_REGION,
         service=TEST_SERVICE)
     resolver.load(test_string, PARAMS)
     self.assertEqual(resolver.render(), "mgmt.ellationeng")
Exemple #3
0
 def test_fully_qualified_env(self, mock_create_aws):
     """Does {{ENV_FULL}} resolve correctly"""
     mock_create_aws.return_value = self._clients
     # alpha0
     test_string = "{{ENV_FULL}}"
     resolver = EFTemplateResolver(profile=get_account_alias("alpha0"),
                                   env="alpha0",
                                   region=TEST_REGION,
                                   service=TEST_SERVICE)
     resolver.load(test_string, PARAMS)
     self.assertEqual(resolver.render(), "alpha0")
     # prod
     resolver = EFTemplateResolver(profile=get_account_alias("test"),
                                   env="test",
                                   region=TEST_REGION,
                                   service=TEST_SERVICE)
     resolver.load(test_string, PARAMS)
     self.assertEqual(resolver.render(), "test")
     # mgmt.testaccount
     resolver = EFTemplateResolver(
         profile=get_account_alias("mgmt.testaccount"),
         env="mgmt.testaccount",
         region=TEST_REGION,
         service=TEST_SERVICE)
     resolver.load(test_string, PARAMS)
     self.assertEqual(resolver.render(), "mgmt.testaccount")
Exemple #4
0
    def test_get_account_alias(self):
        """
    Checks if get_account_alias returns the correct account based on valid environments

    Returns:
      None

    Raises:
      AssertionError if any of the assert checks fail
    """
        for env, account_alias in EFConfig.ENV_ACCOUNT_MAP.items():
            # Attach a numeric value to environments that are ephemeral
            if env in EFConfig.EPHEMERAL_ENVS:
                env += '0'
            self.assertEquals(ef_utils.get_account_alias(env), account_alias)

        # Do tests for global and mgmt envs, which have a special mapping, Example: global.account_alias
        if "global" in EFConfig.ENV_ACCOUNT_MAP:
            for account_alias in EFConfig.ENV_ACCOUNT_MAP.values():
                self.assertEquals(
                    ef_utils.get_account_alias("global." + account_alias),
                    account_alias)
        if "mgmt" in EFConfig.ENV_ACCOUNT_MAP:
            for account_alias in EFConfig.ENV_ACCOUNT_MAP.values():
                self.assertEquals(
                    ef_utils.get_account_alias("mgmt." + account_alias),
                    account_alias)
Exemple #5
0
def handle_args_and_set_context(args):
    """
  Args:
    args: the command line args, probably passed from main() as sys.argv[1:]
  Returns:
    a populated Context object based on CLI args
  """
    parser = argparse.ArgumentParser()
    parser.add_argument("env", help="environment")
    parser.add_argument("path_to_template",
                        help="path to the config template to process")
    parser.add_argument("--no_params",
                        help="disable loading values from params file",
                        action="store_true",
                        default=False)
    parser.add_argument("--verbose",
                        help="Output extra info",
                        action="store_true",
                        default=False)
    parsed = vars(parser.parse_args(args))
    path_to_template = abspath(parsed["path_to_template"])
    service = path_to_template.split('/')[-3]

    return Context(get_account_alias(parsed["env"]), EFConfig.DEFAULT_REGION,
                   parsed["env"], service, path_to_template,
                   parsed["no_params"], parsed["verbose"])
Exemple #6
0
 def test_render_multiline_string_from_list(self, mock_create_aws):
     """Does {{multi}} resolve correctly as a multiline string from yaml parameters file"""
     mock_create_aws.return_value = self._clients
     test_string = "{{multi2}}"
     resolver = EFTemplateResolver(profile=get_account_alias("test"),
                                   env="test",
                                   region=TEST_REGION,
                                   service=TEST_SERVICE)
     with open(self.test_params_json) as json_file:
         resolver.load(test_string, json_file)
     self.assertEqual(resolver.render(), "one\ntwo\nthree")
Exemple #7
0
 def test_load_yaml_file(self, mock_create_aws):
     """Does {{one}} resolve correctly from yaml parameters file"""
     mock_create_aws.return_value = self._clients
     test_string = "{{one}}"
     resolver = EFTemplateResolver(profile=get_account_alias("alpha0"),
                                   env="alpha0",
                                   region=TEST_REGION,
                                   service=TEST_SERVICE)
     with open(self.test_params_yaml) as yaml_file:
         resolver.load(test_string, yaml_file)
     self.assertEqual(resolver.render(), "alpha one")
Exemple #8
0
 def test_render_multiline_string(self, mock_create_aws):
     """Does {{multi}} resolve correctly as a multiline string from yaml parameters file"""
     mock_create_aws.return_value = self._clients
     test_string = "{{multi}}"
     resolver = EFTemplateResolver(profile=get_account_alias("test"),
                                   env="test",
                                   region=TEST_REGION,
                                   service=TEST_SERVICE)
     with open(self.test_params_yaml) as yaml_file:
         resolver.load(test_string, yaml_file)
     self.assertEqual(
         resolver.render(),
         "thisisareallylongstringthatcoversmultiple\nlinesfortestingmultilinestrings"
     )
Exemple #9
0
 def env(self, value):
     """
 Sets context.env, context.env_short, and context.account_alias if env is valid
 For envs of the form "global.<account>" and "mgmt.<account_alias>",
 env is captured as "global" or "mgmt" and account_alias is parsed out of the full env rather than looked up
 Args:
   value: the fully-qualified env value
 Raises:
   ValueError if env is not valid
 """
     env_valid(value)
     self._env_full = value
     if value.find(".") == -1:
         # plain environment, e.g. prod, staging, proto<n>
         self._env = value
         self._account_alias = get_account_alias(value)
     else:
         # "<env>.<account_alias>" form, e.g. global.ellationeng or mgmt.ellationeng
         self._env, self._account_alias = value.split(".")
         # since we extracted an env, must reconfirm that it's legit
         global_env_valid(self._env)
     self._env_short = get_env_short(value)
Exemple #10
0
class TestEFVersionResolver(unittest.TestCase):
  """Tests for 'ef_version_resolver.py'"""

  # initialize based on where running
  where = whereami()
  if where == "local":
    session = boto3.Session(profile_name=get_account_alias("proto0"), region_name=EFConfig.DEFAULT_REGION)
  elif where == "ec2":
    region = http_get_metadata("placement/availability-zone/")
    region = region[:-1]
    session = boto3.Session(region_name=region)
  else:
    fail("Can't test in environment: " + where)

  clients = {
    "ec2": session.client("ec2")
  }

  def test_ami_id(self):
    """Does ami-id,data-api resolve to an AMI id"""
    test_string = "ami-id,data-api"
    resolver = EFVersionResolver(TestEFVersionResolver.clients)
    self.assertRegexpMatches(resolver.lookup(test_string), "^ami-[a-f0-9]{8}$")
Exemple #11
0
    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import unittest

from ef_config import EFConfig
from ef_template_resolver import EFTemplateResolver
from ef_utils import get_account_alias

TEST_PROFILE = get_account_alias("proto0")
TEST_REGION = EFConfig.DEFAULT_REGION
TEST_ENV = "proto0"
TEST_SERVICE = "none"

PARAMS = """{
  "params":{
    "default":{
      "one": "default one",
      "two": "default two",
      "o": "o",
      "ne": "ne",
      "/_-.": "slashunderscoredashdot",
      ".": "dot",
      "my-thing": "my-hyphen-thing"
    },
Exemple #12
0
VPC CIDR block: {{aws:ec2:vpc/cidrblock,vpc-staging}}\n\
WAF Web ACL ID: {{aws:waf:web-acl-id,staging-StaticAcl}}\n\
SSL Certificate ARN us-west-2/cx-proto3.com: {{aws:acm:certificate-arn,us-west-2/cx-proto3.com}}\n\
Elastic network interface (ENI) eni-proto3-dnsproxy-1a: {{aws:ec2:eni/eni-id,eni-proto3-dnsproxy-1a}}\n\
Elastic IP Allocation ID: {{aws:ec2:elasticip/elasticip-id,ElasticIpMgmtCingest1}}\n\
Elastic IP IP Address: {{aws:ec2:elasticip/elasticip-ipaddress,ElasticIpMgmtCingest1}}\n\
EFConfig resolver, accountaliasofenv,prod: {{efconfig:accountaliasofenv,staging}}\n\
AMI lookup: {{version:ami-id,proto0/test-instance}}\n\
Latest AMI for test-instance: {{version:ami-id,proto0/test-instance}}\
"

GLOBAL_ENV_TEST_STRING = "fully-qualified environment:{{ENV_FULL}}\n"

# Test with proto0
if LOCAL:
    resolver = EFTemplateResolver(profile=get_account_alias("proto0"),
                                  env="proto0",
                                  region="us-west-2",
                                  service="mine",
                                  verbose=True)
else:
    resolver = EFTemplateResolver(verbose=True)

resolver.load(TEST_STRING, PARAMS)
resolver.render()

print(resolver.template)
print("unresolved symbol count: " + str(len(resolver.unresolved_symbols())))
print("unresolved symbols: " + repr(resolver.unresolved_symbols()))
print("all template symbols: " + repr(resolver.symbols))
print("all EFTemplateResolver symbols: " + repr(resolver.resolved))
Exemple #13
0
limitations under the License.
"""

import os
import unittest

from mock import call, Mock, patch

# For local application imports, context_paths must be first despite lexicon ordering
import context_paths

from ef_config import EFConfig
from ef_template_resolver import EFTemplateResolver
from ef_utils import get_account_alias

TEST_PROFILE = get_account_alias("test")
TEST_REGION = EFConfig.DEFAULT_REGION
TEST_ENV = "test"
TEST_SERVICE = "none"

PARAMS = """{
  "params":{
    "default":{
      "one": "default one",
      "two": "default two",
      "o": "o",
      "ne": "ne",
      "/_-.": "slashunderscoredashdot",
      ".": "dot",
      "my-thing": "my-hyphen-thing"
    },
Exemple #14
0
 def test_get_account_alias(self):
     """Does get_account_alias resolve correctly"""
     self.assertEquals(get_account_alias("prod"), "ellation")
     self.assertEquals(get_account_alias("staging"), "ellationeng")
     self.assertEquals(get_account_alias("proto0"), "ellationeng")
     self.assertEquals(get_account_alias("global.ellation"), "ellation")