add indirection to access account id (#5098)

This commit is contained in:
Thomas Rausch 2022-05-09 00:25:40 +02:00 committed by GitHub
parent 551df91ddf
commit e911341e6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
119 changed files with 477 additions and 438 deletions

View File

@ -13,7 +13,7 @@ import cryptography.hazmat.primitives.asymmetric.rsa
from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.core import get_account_id
AWS_ROOT_CA = b"""-----BEGIN CERTIFICATE----- AWS_ROOT_CA = b"""-----BEGIN CERTIFICATE-----
@ -161,7 +161,7 @@ class CertBundle(BaseModel):
# Used for when one wants to overwrite an arn # Used for when one wants to overwrite an arn
if arn is None: if arn is None:
self.arn = make_arn_for_certificate(DEFAULT_ACCOUNT_ID, region) self.arn = make_arn_for_certificate(get_account_id(), region)
else: else:
self.arn = arn self.arn = arn
@ -444,7 +444,7 @@ class AWSCertificateManagerBackend(BaseBackend):
@staticmethod @staticmethod
def _arn_not_found(arn): def _arn_not_found(arn):
msg = "Certificate with arn {0} not found in account {1}".format( msg = "Certificate with arn {0} not found in account {1}".format(
arn, DEFAULT_ACCOUNT_ID arn, get_account_id()
) )
return AWSResourceNotFoundException(msg) return AWSResourceNotFoundException(msg)

View File

@ -10,7 +10,7 @@ import time
from urllib.parse import urlparse from urllib.parse import urlparse
import responses import responses
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel, CloudFormationModel from moto.core import get_account_id, BaseBackend, BaseModel, CloudFormationModel
from .utils import create_id, to_path from .utils import create_id, to_path
from moto.core.utils import path_url, BackendDict from moto.core.utils import path_url, BackendDict
from .integration_parsers.aws_parser import TypeAwsParser from .integration_parsers.aws_parser import TypeAwsParser
@ -1492,7 +1492,7 @@ class APIGatewayBackend(BaseBackend):
): ):
resource = self.get_resource(function_id, resource_id) resource = self.get_resource(function_id, resource_id)
if credentials and not re.match( if credentials and not re.match(
"^arn:aws:iam::" + str(ACCOUNT_ID), credentials "^arn:aws:iam::" + str(get_account_id()), credentials
): ):
raise CrossAccountNotAllowed() raise CrossAccountNotAllowed()
if not integration_method and integration_type in [ if not integration_method and integration_type in [

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.ecs import ecs_backends from moto.ecs import ecs_backends
from .exceptions import AWSValidationException from .exceptions import AWSValidationException
@ -450,7 +450,7 @@ class FakeScheduledAction(BaseModel):
scalable_target_action, scalable_target_action,
region, region,
): ):
self.arn = f"arn:aws:autoscaling:{region}:{ACCOUNT_ID}:scheduledAction:{service_namespace}:scheduledActionName/{scheduled_action_name}" self.arn = f"arn:aws:autoscaling:{region}:{get_account_id()}:scheduledAction:{service_namespace}:scheduledActionName/{scheduled_action_name}"
self.service_namespace = service_namespace self.service_namespace = service_namespace
self.schedule = schedule self.schedule = schedule
self.timezone = timezone self.timezone = timezone

View File

@ -1,6 +1,6 @@
import base64 import base64
from datetime import timedelta, datetime, timezone from datetime import timedelta, datetime, timezone
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict, unix_time from moto.core.utils import BackendDict, unix_time
from moto.utilities.tagging_service import TaggingService from moto.utilities.tagging_service import TaggingService
@ -74,7 +74,9 @@ class GraphqlAPI(BaseModel):
self.user_pool_config = user_pool_config self.user_pool_config = user_pool_config
self.xray_enabled = xray_enabled self.xray_enabled = xray_enabled
self.arn = f"arn:aws:appsync:{self.region}:{ACCOUNT_ID}:apis/{self.api_id}" self.arn = (
f"arn:aws:appsync:{self.region}:{get_account_id()}:apis/{self.api_id}"
)
self.graphql_schema = None self.graphql_schema = None
self.api_keys = dict() self.api_keys = dict()

View File

@ -1,6 +1,6 @@
import time import time
from moto.core import BaseBackend, BaseModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, get_account_id
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from uuid import uuid4 from uuid import uuid4
@ -18,7 +18,9 @@ class TaggableResourceMixin(object):
@property @property
def arn(self): def arn(self):
return "arn:aws:athena:{region}:{account_id}:{resource_name}".format( return "arn:aws:athena:{region}:{account_id}:{resource_name}".format(
region=self.region, account_id=ACCOUNT_ID, resource_name=self.resource_name region=self.region,
account_id=get_account_id(),
resource_name=self.resource_name,
) )
def create_tags(self, tags): def create_tags(self, tags):

View File

@ -9,7 +9,7 @@ from moto.packages.boto.ec2.blockdevicemapping import (
from moto.ec2.exceptions import InvalidInstanceIdError from moto.ec2.exceptions import InvalidInstanceIdError
from collections import OrderedDict from collections import OrderedDict
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel, CloudFormationModel from moto.core import get_account_id, BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import camelcase_to_underscores, BackendDict from moto.core.utils import camelcase_to_underscores, BackendDict
from moto.ec2 import ec2_backends from moto.ec2 import ec2_backends
from moto.elb import elb_backends from moto.elb import elb_backends
@ -97,7 +97,7 @@ class FakeScalingPolicy(BaseModel):
@property @property
def arn(self): def arn(self):
return f"arn:aws:autoscaling:{self.autoscaling_backend.region}:{ACCOUNT_ID}:scalingPolicy:c322761b-3172-4d56-9a21-0ed9d6161d67:autoScalingGroupName/{self.as_name}:policyName/{self.name}" return f"arn:aws:autoscaling:{self.autoscaling_backend.region}:{get_account_id()}:scalingPolicy:c322761b-3172-4d56-9a21-0ed9d6161d67:autoScalingGroupName/{self.as_name}:policyName/{self.name}"
def execute(self): def execute(self):
if self.adjustment_type == "ExactCapacity": if self.adjustment_type == "ExactCapacity":
@ -153,7 +153,7 @@ class FakeLaunchConfiguration(CloudFormationModel):
self.metadata_options = metadata_options self.metadata_options = metadata_options
self.classic_link_vpc_id = classic_link_vpc_id self.classic_link_vpc_id = classic_link_vpc_id
self.classic_link_vpc_security_groups = classic_link_vpc_security_groups self.classic_link_vpc_security_groups = classic_link_vpc_security_groups
self.arn = f"arn:aws:autoscaling:{region_name}:{ACCOUNT_ID}:launchConfiguration:9dbbbf87-6141-428a-a409-0752edbe6cad:launchConfigurationName/{self.name}" self.arn = f"arn:aws:autoscaling:{region_name}:{get_account_id()}:launchConfiguration:9dbbbf87-6141-428a-a409-0752edbe6cad:launchConfigurationName/{self.name}"
@classmethod @classmethod
def create_from_instance(cls, name, instance, backend): def create_from_instance(cls, name, instance, backend):
@ -348,7 +348,7 @@ class FakeAutoScalingGroup(CloudFormationModel):
@property @property
def arn(self): def arn(self):
return f"arn:aws:autoscaling:{self.region}:{ACCOUNT_ID}:autoScalingGroup:{self._id}:autoScalingGroupName/{self.name}" return f"arn:aws:autoscaling:{self.region}:{get_account_id()}:autoScalingGroup:{self._id}:autoScalingGroupName/{self.name}"
def active_instances(self): def active_instances(self):
return [x for x in self.instance_states if x.lifecycle_state == "InService"] return [x for x in self.instance_states if x.lifecycle_state == "InService"]

View File

@ -50,7 +50,7 @@ from .utils import (
from moto.sqs import sqs_backends from moto.sqs import sqs_backends
from moto.dynamodb import dynamodb_backends from moto.dynamodb import dynamodb_backends
from moto.dynamodbstreams import dynamodbstreams_backends from moto.dynamodbstreams import dynamodbstreams_backends
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.utilities.docker_utilities import DockerModel, parse_image_ref from moto.utilities.docker_utilities import DockerModel, parse_image_ref
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from uuid import uuid4 from uuid import uuid4
@ -258,7 +258,9 @@ class LayerVersion(CloudFormationModel):
@property @property
def arn(self): def arn(self):
if self.version: if self.version:
return make_layer_ver_arn(self.region, ACCOUNT_ID, self.name, self.version) return make_layer_ver_arn(
self.region, get_account_id(), self.name, self.version
)
raise ValueError("Layer version is not set") raise ValueError("Layer version is not set")
def attach(self, layer, version): def attach(self, layer, version):
@ -315,9 +317,7 @@ class LambdaAlias(BaseModel):
def __init__( def __init__(
self, region, name, function_name, function_version, description, routing_config self, region, name, function_name, function_version, description, routing_config
): ):
self.arn = ( self.arn = f"arn:aws:lambda:{region}:{get_account_id()}:function:{function_name}:{name}"
f"arn:aws:lambda:{region}:{ACCOUNT_ID}:function:{function_name}:{name}"
)
self.name = name self.name = name
self.function_version = function_version self.function_version = function_version
self.description = description self.description = description
@ -348,7 +348,7 @@ class Layer(object):
self.region = region self.region = region
self.name = name self.name = name
self.layer_arn = make_layer_arn(region, ACCOUNT_ID, self.name) self.layer_arn = make_layer_arn(region, get_account_id(), self.name)
self._latest_version = 0 self._latest_version = 0
self.layer_versions = {} self.layer_versions = {}
@ -435,7 +435,7 @@ class LambdaFunction(CloudFormationModel, DockerModel):
self.code_sha_256 = "" self.code_sha_256 = ""
self.function_arn = make_function_arn( self.function_arn = make_function_arn(
self.region, ACCOUNT_ID, self.function_name self.region, get_account_id(), self.function_name
) )
if spec.get("Tags"): if spec.get("Tags"):
@ -447,7 +447,7 @@ class LambdaFunction(CloudFormationModel, DockerModel):
def set_version(self, version): def set_version(self, version):
self.function_arn = make_function_ver_arn( self.function_arn = make_function_ver_arn(
self.region, ACCOUNT_ID, self.function_name, version self.region, get_account_id(), self.function_name, version
) )
self.version = version self.version = version
self.last_modified = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") self.last_modified = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
@ -821,7 +821,7 @@ class LambdaFunction(CloudFormationModel, DockerModel):
from moto.cloudformation.exceptions import UnformattedGetAttTemplateException from moto.cloudformation.exceptions import UnformattedGetAttTemplateException
if attribute_name == "Arn": if attribute_name == "Arn":
return make_function_arn(self.region, ACCOUNT_ID, self.function_name) return make_function_arn(self.region, get_account_id(), self.function_name)
raise UnformattedGetAttTemplateException() raise UnformattedGetAttTemplateException()
@classmethod @classmethod
@ -856,7 +856,7 @@ class LambdaFunction(CloudFormationModel, DockerModel):
def get_alias(self, name): def get_alias(self, name):
if name in self._aliases: if name in self._aliases:
return self._aliases[name] return self._aliases[name]
arn = f"arn:aws:lambda:{self.region}:{ACCOUNT_ID}:function:{self.function_name}:{name}" arn = f"arn:aws:lambda:{self.region}:{get_account_id()}:function:{self.function_name}:{name}"
raise UnknownAliasException(arn) raise UnknownAliasException(arn)
def put_alias(self, name, description, function_version, routing_config): def put_alias(self, name, description, function_version, routing_config):
@ -1102,7 +1102,7 @@ class LambdaStorage(object):
if name_or_arn.startswith("arn:aws"): if name_or_arn.startswith("arn:aws"):
arn = name_or_arn arn = name_or_arn
else: else:
arn = make_function_arn(self.region_name, ACCOUNT_ID, name_or_arn) arn = make_function_arn(self.region_name, get_account_id(), name_or_arn)
if qualifier: if qualifier:
arn = f"{arn}:{qualifier}" arn = f"{arn}:{qualifier}"
raise UnknownFunctionException(arn) raise UnknownFunctionException(arn)
@ -1116,7 +1116,7 @@ class LambdaStorage(object):
valid_role = re.match(InvalidRoleFormat.pattern, fn.role) valid_role = re.match(InvalidRoleFormat.pattern, fn.role)
if valid_role: if valid_role:
account = valid_role.group(2) account = valid_role.group(2)
if account != ACCOUNT_ID: if account != get_account_id():
raise CrossAccountNotAllowed() raise CrossAccountNotAllowed()
try: try:
iam_backend.get_role_by_arn(fn.role) iam_backend.get_role_by_arn(fn.role)
@ -1577,7 +1577,7 @@ class LambdaBackend(BaseBackend):
): ):
data = { data = {
"messageType": "DATA_MESSAGE", "messageType": "DATA_MESSAGE",
"owner": ACCOUNT_ID, "owner": get_account_id(),
"logGroup": log_group_name, "logGroup": log_group_name,
"logStream": log_stream_name, "logStream": log_stream_name,
"subscriptionFilters": [filter_name], "subscriptionFilters": [filter_name],

View File

@ -9,7 +9,7 @@ import threading
import dateutil.parser import dateutil.parser
from sys import platform from sys import platform
from moto.core import BaseBackend, BaseModel, CloudFormationModel from moto.core import BaseBackend, BaseModel, CloudFormationModel, get_account_id
from moto.iam import iam_backends from moto.iam import iam_backends
from moto.ec2 import ec2_backends from moto.ec2 import ec2_backends
from moto.ecs import ecs_backends from moto.ecs import ecs_backends
@ -27,7 +27,6 @@ from moto.ec2.exceptions import InvalidSubnetIdError
from moto.ec2.models.instance_types import INSTANCE_TYPES as EC2_INSTANCE_TYPES from moto.ec2.models.instance_types import INSTANCE_TYPES as EC2_INSTANCE_TYPES
from moto.ec2.models.instance_types import INSTANCE_FAMILIES as EC2_INSTANCE_FAMILIES from moto.ec2.models.instance_types import INSTANCE_FAMILIES as EC2_INSTANCE_FAMILIES
from moto.iam.exceptions import IAMNotFoundException from moto.iam.exceptions import IAMNotFoundException
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID
from moto.core.utils import unix_time_millis, BackendDict from moto.core.utils import unix_time_millis, BackendDict
from moto.moto_api import state_manager from moto.moto_api import state_manager
from moto.moto_api._internal.managed_state_model import ManagedState from moto.moto_api._internal.managed_state_model import ManagedState
@ -69,7 +68,7 @@ class ComputeEnvironment(CloudFormationModel):
self.compute_resources = compute_resources self.compute_resources = compute_resources
self.service_role = service_role self.service_role = service_role
self.arn = make_arn_for_compute_env( self.arn = make_arn_for_compute_env(
DEFAULT_ACCOUNT_ID, compute_environment_name, region_name get_account_id(), compute_environment_name, region_name
) )
self.instances = [] self.instances = []
@ -146,7 +145,7 @@ class JobQueue(CloudFormationModel):
self.state = state self.state = state
self.environments = environments self.environments = environments
self.env_order_json = env_order_json self.env_order_json = env_order_json
self.arn = make_arn_for_job_queue(DEFAULT_ACCOUNT_ID, name, region_name) self.arn = make_arn_for_job_queue(get_account_id(), name, region_name)
self.status = "VALID" self.status = "VALID"
self.backend = backend self.backend = backend
@ -258,7 +257,7 @@ class JobDefinition(CloudFormationModel):
def _update_arn(self): def _update_arn(self):
self.revision += 1 self.revision += 1
self.arn = make_arn_for_task_def( self.arn = make_arn_for_task_def(
DEFAULT_ACCOUNT_ID, self.name, self.revision, self._region get_account_id(), self.name, self.revision, self._region
) )
def _get_resource_requirement(self, req_type, default=None): def _get_resource_requirement(self, req_type, default=None):

View File

@ -7,8 +7,7 @@ from collections import OrderedDict
from yaml.parser import ParserError # pylint:disable=c-extension-no-member from yaml.parser import ParserError # pylint:disable=c-extension-no-member
from yaml.scanner import ScannerError # pylint:disable=c-extension-no-member from yaml.scanner import ScannerError # pylint:disable=c-extension-no-member
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel, get_account_id
from moto.core.models import ACCOUNT_ID
from moto.core.utils import ( from moto.core.utils import (
iso_8601_datetime_with_milliseconds, iso_8601_datetime_with_milliseconds,
iso_8601_datetime_without_milliseconds, iso_8601_datetime_without_milliseconds,
@ -503,7 +502,7 @@ ClientRequestToken='{client_request_token}'""".format(
timestamp=iso_8601_datetime_with_milliseconds(self.timestamp), timestamp=iso_8601_datetime_with_milliseconds(self.timestamp),
event_id=self.event_id, event_id=self.event_id,
logical_resource_id=self.logical_resource_id, logical_resource_id=self.logical_resource_id,
account_id=ACCOUNT_ID, account_id=get_account_id(),
resource_properties=self.resource_properties, resource_properties=self.resource_properties,
resource_status=self.resource_status, resource_status=self.resource_status,
resource_status_reason=self.resource_status_reason, resource_status_reason=self.resource_status_reason,

View File

@ -46,7 +46,7 @@ from moto.ssm import models # noqa # pylint: disable=all
# End ugly list of imports # End ugly list of imports
from moto.core import ACCOUNT_ID, CloudFormationModel from moto.core import get_account_id, CloudFormationModel
from moto.s3 import s3_backend from moto.s3 import s3_backend
from moto.s3.utils import bucket_and_name_from_url from moto.s3.utils import bucket_and_name_from_url
from moto.ssm import ssm_backends from moto.ssm import ssm_backends
@ -453,7 +453,7 @@ class ResourceMap(collections_abc.Mapping):
# Create the default resources # Create the default resources
self._parsed_resources = { self._parsed_resources = {
"AWS::AccountId": ACCOUNT_ID, "AWS::AccountId": get_account_id(),
"AWS::Region": self._region_name, "AWS::Region": self._region_name,
"AWS::StackId": stack_id, "AWS::StackId": stack_id,
"AWS::StackName": stack_name, "AWS::StackName": stack_name,

View File

@ -8,7 +8,7 @@ from moto.core.responses import BaseResponse
from moto.core.utils import amzn_request_id from moto.core.utils import amzn_request_id
from moto.s3 import s3_backend from moto.s3 import s3_backend
from moto.s3.exceptions import S3ClientError from moto.s3.exceptions import S3ClientError
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from .models import cloudformation_backends from .models import cloudformation_backends
from .exceptions import ValidationError, MissingParameterError from .exceptions import ValidationError, MissingParameterError
from .utils import yaml_tag_constructor from .utils import yaml_tag_constructor
@ -516,7 +516,7 @@ class CloudFormationResponse(BaseResponse):
if not stackset.admin_role: if not stackset.admin_role:
stackset.admin_role = "arn:aws:iam::{AccountId}:role/AWSCloudFormationStackSetAdministrationRole".format( stackset.admin_role = "arn:aws:iam::{AccountId}:role/AWSCloudFormationStackSetAdministrationRole".format(
AccountId=ACCOUNT_ID AccountId=get_account_id()
) )
if not stackset.execution_role: if not stackset.execution_role:
stackset.execution_role = "AWSCloudFormationStackSetExecutionRole" stackset.execution_role = "AWSCloudFormationStackSetExecutionRole"
@ -1175,7 +1175,7 @@ DESCRIBE_STACKSET_OPERATION_RESPONSE_TEMPLATE = (
<StackSetOperation> <StackSetOperation>
<ExecutionRoleName>{{ stackset.execution_role }}</ExecutionRoleName> <ExecutionRoleName>{{ stackset.execution_role }}</ExecutionRoleName>
<AdministrationRoleARN>arn:aws:iam::""" <AdministrationRoleARN>arn:aws:iam::"""
+ ACCOUNT_ID + get_account_id()
+ """:role/{{ stackset.admin_role }}</AdministrationRoleARN> + """:role/{{ stackset.admin_role }}</AdministrationRoleARN>
<StackSetId>{{ stackset.id }}</StackSetId> <StackSetId>{{ stackset.id }}</StackSetId>
<CreationTimestamp>{{ operation.CreationTimestamp }}</CreationTimestamp> <CreationTimestamp>{{ operation.CreationTimestamp }}</CreationTimestamp>
@ -1204,7 +1204,7 @@ LIST_STACK_SET_OPERATION_RESULTS_RESPONSE_TEMPLATE = (
<member> <member>
<AccountGateResult> <AccountGateResult>
<StatusReason>Function not found: arn:aws:lambda:us-west-2:""" <StatusReason>Function not found: arn:aws:lambda:us-west-2:"""
+ ACCOUNT_ID + get_account_id()
+ """:function:AWSCloudFormationStackSetAccountGate</StatusReason> + """:function:AWSCloudFormationStackSetAccountGate</StatusReason>
<Status>SKIPPED</Status> <Status>SKIPPED</Status>
</AccountGateResult> </AccountGateResult>

View File

@ -4,10 +4,10 @@ import yaml
import os import os
import string import string
from moto.core import ACCOUNT_ID from moto.core import get_account_id
def generate_stack_id(stack_name, region="us-east-1", account=ACCOUNT_ID): def generate_stack_id(stack_name, region="us-east-1", account=get_account_id()):
random_id = uuid.uuid4() random_id = uuid.uuid4()
return "arn:aws:cloudformation:{}:{}:stack/{}/{}".format( return "arn:aws:cloudformation:{}:{}:stack/{}/{}".format(
region, account, stack_name, random_id region, account, stack_name, random_id
@ -17,7 +17,7 @@ def generate_stack_id(stack_name, region="us-east-1", account=ACCOUNT_ID):
def generate_changeset_id(changeset_name, region_name): def generate_changeset_id(changeset_name, region_name):
random_id = uuid.uuid4() random_id = uuid.uuid4()
return "arn:aws:cloudformation:{0}:{1}:changeSet/{2}/{3}".format( return "arn:aws:cloudformation:{0}:{1}:changeSet/{2}/{3}".format(
region_name, ACCOUNT_ID, changeset_name, random_id region_name, get_account_id(), changeset_name, random_id
) )
@ -28,7 +28,7 @@ def generate_stackset_id(stackset_name):
def generate_stackset_arn(stackset_id, region_name): def generate_stackset_arn(stackset_id, region_name):
return "arn:aws:cloudformation:{}:{}:stackset/{}".format( return "arn:aws:cloudformation:{}:{}:stackset/{}".format(
region_name, ACCOUNT_ID, stackset_id region_name, get_account_id(), stackset_id
) )

View File

@ -1,7 +1,7 @@
import random import random
import string import string
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.moto_api import state_manager from moto.moto_api import state_manager
from moto.moto_api._internal.managed_state_model import ManagedState from moto.moto_api._internal.managed_state_model import ManagedState
from uuid import uuid4 from uuid import uuid4
@ -149,7 +149,7 @@ class Distribution(BaseModel, ManagedState):
# Configure internal properties # Configure internal properties
self.distribution_id = Distribution.random_id() self.distribution_id = Distribution.random_id()
self.arn = ( self.arn = (
f"arn:aws:cloudfront:{ACCOUNT_ID}:distribution/{self.distribution_id}" f"arn:aws:cloudfront:{get_account_id()}:distribution/{self.distribution_id}"
) )
self.distribution_config = DistributionConfig(config) self.distribution_config = DistributionConfig(config)
self.active_trusted_signers = ActiveTrustedSigners() self.active_trusted_signers = ActiveTrustedSigners()

View File

@ -1,5 +1,5 @@
"""Exceptions raised by the cloudtrail service.""" """Exceptions raised by the cloudtrail service."""
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.exceptions import JsonRESTError from moto.core.exceptions import JsonRESTError
@ -30,7 +30,7 @@ class TrailNotFoundException(JsonRESTError):
def __init__(self, name): def __init__(self, name):
super().__init__( super().__init__(
"TrailNotFoundException", "TrailNotFoundException",
f"Unknown trail: {name} for the user: {ACCOUNT_ID}", f"Unknown trail: {name} for the user: {get_account_id()}",
) )

View File

@ -2,7 +2,7 @@ import re
import time import time
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict
from moto.utilities.tagging_service import TaggingService from moto.utilities.tagging_service import TaggingService
from .exceptions import ( from .exceptions import (
@ -109,12 +109,12 @@ class Trail(BaseModel):
@property @property
def arn(self): def arn(self):
return f"arn:aws:cloudtrail:{self.region_name}:{ACCOUNT_ID}:trail/{self.trail_name}" return f"arn:aws:cloudtrail:{self.region_name}:{get_account_id()}:trail/{self.trail_name}"
@property @property
def topic_arn(self): def topic_arn(self):
if self.sns_topic_name: if self.sns_topic_name:
return f"arn:aws:sns:{self.region_name}:{ACCOUNT_ID}:{self.sns_topic_name}" return f"arn:aws:sns:{self.region_name}:{get_account_id()}:{self.sns_topic_name}"
return None return None
def check_name(self): def check_name(self):
@ -303,7 +303,9 @@ class CloudTrailBackend(BaseBackend):
) )
if not trail_name: if not trail_name:
# This particular method returns the ARN as part of the error message # This particular method returns the ARN as part of the error message
arn = f"arn:aws:cloudtrail:{self.region_name}:{ACCOUNT_ID}:trail/{name}" arn = (
f"arn:aws:cloudtrail:{self.region_name}:{get_account_id()}:trail/{name}"
)
raise TrailNotFoundException(name=arn) raise TrailNotFoundException(name=arn)
trail = self.trails[trail_name] trail = self.trails[trail_name]
return trail.status return trail.status

View File

@ -20,7 +20,7 @@ from .exceptions import (
from .utils import make_arn_for_dashboard, make_arn_for_alarm from .utils import make_arn_for_dashboard, make_arn_for_alarm
from dateutil import parser from dateutil import parser
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.core import get_account_id
from ..utilities.tagging_service import TaggingService from ..utilities.tagging_service import TaggingService
_EMPTY_LIST = tuple() _EMPTY_LIST = tuple()
@ -129,7 +129,7 @@ class FakeAlarm(BaseModel):
): ):
self.region_name = region_name self.region_name = region_name
self.name = name self.name = name
self.alarm_arn = make_arn_for_alarm(region_name, DEFAULT_ACCOUNT_ID, name) self.alarm_arn = make_arn_for_alarm(region_name, get_account_id(), name)
self.namespace = namespace self.namespace = namespace
self.metric_name = metric_name self.metric_name = metric_name
self.metric_data_queries = metric_data_queries self.metric_data_queries = metric_data_queries
@ -240,7 +240,7 @@ class MetricDatum(BaseModel):
class Dashboard(BaseModel): class Dashboard(BaseModel):
def __init__(self, name, body): def __init__(self, name, body):
# Guaranteed to be unique for now as the name is also the key of a dictionary where they are stored # Guaranteed to be unique for now as the name is also the key of a dictionary where they are stored
self.arn = make_arn_for_dashboard(DEFAULT_ACCOUNT_ID, name) self.arn = make_arn_for_dashboard(get_account_id(), name)
self.name = name self.name = name
self.body = body self.body = body
self.last_modified = datetime.now() self.last_modified = datetime.now()

View File

@ -1,7 +1,7 @@
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from .exceptions import RepositoryDoesNotExistException, RepositoryNameExistsException from .exceptions import RepositoryDoesNotExistException, RepositoryNameExistsException
import uuid import uuid
@ -26,9 +26,9 @@ class CodeCommit(BaseModel):
self.repository_metadata["repositoryDescription"] = repository_description self.repository_metadata["repositoryDescription"] = repository_description
self.repository_metadata["repositoryId"] = str(uuid.uuid4()) self.repository_metadata["repositoryId"] = str(uuid.uuid4())
self.repository_metadata["Arn"] = "arn:aws:codecommit:{0}:{1}:{2}".format( self.repository_metadata["Arn"] = "arn:aws:codecommit:{0}:{1}:{2}".format(
region, ACCOUNT_ID, repository_name region, get_account_id(), repository_name
) )
self.repository_metadata["accountId"] = ACCOUNT_ID self.repository_metadata["accountId"] = get_account_id()
class CodeCommitBackend(BaseBackend): class CodeCommitBackend(BaseBackend):

View File

@ -14,7 +14,7 @@ from moto.codepipeline.exceptions import (
InvalidTagsException, InvalidTagsException,
TooManyTagsException, TooManyTagsException,
) )
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
class CodePipeline(BaseModel): class CodePipeline(BaseModel):
@ -26,7 +26,7 @@ class CodePipeline(BaseModel):
self.tags = {} self.tags = {}
self._arn = "arn:aws:codepipeline:{0}:{1}:{2}".format( self._arn = "arn:aws:codepipeline:{0}:{1}:{2}".format(
region, ACCOUNT_ID, pipeline["name"] region, get_account_id(), pipeline["name"]
) )
self._created = datetime.utcnow() self._created = datetime.utcnow()
self._updated = datetime.utcnow() self._updated = datetime.utcnow()
@ -91,7 +91,7 @@ class CodePipelineBackend(BaseBackend):
if pipeline["name"] in self.pipelines: if pipeline["name"] in self.pipelines:
raise InvalidStructureException( raise InvalidStructureException(
"A pipeline with the name '{0}' already exists in account '{1}'".format( "A pipeline with the name '{0}' already exists in account '{1}'".format(
pipeline["name"], ACCOUNT_ID pipeline["name"], get_account_id()
) )
) )
@ -130,7 +130,7 @@ class CodePipelineBackend(BaseBackend):
if not codepipeline: if not codepipeline:
raise PipelineNotFoundException( raise PipelineNotFoundException(
"Account '{0}' does not have a pipeline with name '{1}'".format( "Account '{0}' does not have a pipeline with name '{1}'".format(
ACCOUNT_ID, name get_account_id(), name
) )
) )
@ -142,7 +142,7 @@ class CodePipelineBackend(BaseBackend):
if not codepipeline: if not codepipeline:
raise ResourceNotFoundException( raise ResourceNotFoundException(
"The account with id '{0}' does not include a pipeline with the name '{1}'".format( "The account with id '{0}' does not include a pipeline with the name '{1}'".format(
ACCOUNT_ID, pipeline["name"] get_account_id(), pipeline["name"]
) )
) )
@ -178,7 +178,7 @@ class CodePipelineBackend(BaseBackend):
if not pipeline: if not pipeline:
raise ResourceNotFoundException( raise ResourceNotFoundException(
"The account with id '{0}' does not include a pipeline with the name '{1}'".format( "The account with id '{0}' does not include a pipeline with the name '{1}'".format(
ACCOUNT_ID, name get_account_id(), name
) )
) )
@ -193,7 +193,7 @@ class CodePipelineBackend(BaseBackend):
if not pipeline: if not pipeline:
raise ResourceNotFoundException( raise ResourceNotFoundException(
"The account with id '{0}' does not include a pipeline with the name '{1}'".format( "The account with id '{0}' does not include a pipeline with the name '{1}'".format(
ACCOUNT_ID, name get_account_id(), name
) )
) )
@ -209,7 +209,7 @@ class CodePipelineBackend(BaseBackend):
if not pipeline: if not pipeline:
raise ResourceNotFoundException( raise ResourceNotFoundException(
"The account with id '{0}' does not include a pipeline with the name '{1}'".format( "The account with id '{0}' does not include a pipeline with the name '{1}'".format(
ACCOUNT_ID, name get_account_id(), name
) )
) )

View File

@ -10,7 +10,7 @@ import random
from jose import jws from jose import jws
from collections import OrderedDict from collections import OrderedDict
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.core import get_account_id
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from .exceptions import ( from .exceptions import (
GroupExistsException, GroupExistsException,
@ -370,7 +370,7 @@ class CognitoIdpUserPool(BaseModel):
self.region = region self.region = region
self.id = "{}_{}".format(self.region, str(uuid.uuid4().hex)) self.id = "{}_{}".format(self.region, str(uuid.uuid4().hex))
self.arn = "arn:aws:cognito-idp:{}:{}:userpool/{}".format( self.arn = "arn:aws:cognito-idp:{}:{}:userpool/{}".format(
self.region, DEFAULT_ACCOUNT_ID, self.id self.region, get_account_id(), self.id
) )
self.name = name self.name = name
self.status = None self.status = None

View File

@ -50,7 +50,7 @@ from moto.config.exceptions import (
) )
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.core import get_account_id
from moto.core.responses import AWSServiceSpec from moto.core.responses import AWSServiceSpec
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.iam.config import role_config_query, policy_config_query from moto.iam.config import role_config_query, policy_config_query
@ -359,7 +359,7 @@ class ConfigAggregator(ConfigEmptyDictable):
self.configuration_aggregator_name = name self.configuration_aggregator_name = name
self.configuration_aggregator_arn = "arn:aws:config:{region}:{id}:config-aggregator/config-aggregator-{random}".format( self.configuration_aggregator_arn = "arn:aws:config:{region}:{id}:config-aggregator/config-aggregator-{random}".format(
region=region, id=DEFAULT_ACCOUNT_ID, random=random_string() region=region, id=get_account_id(), random=random_string()
) )
self.account_aggregation_sources = account_sources self.account_aggregation_sources = account_sources
self.organization_aggregation_source = org_source self.organization_aggregation_source = org_source
@ -397,7 +397,7 @@ class ConfigAggregationAuthorization(ConfigEmptyDictable):
"arn:aws:config:{region}:{id}:aggregation-authorization/" "arn:aws:config:{region}:{id}:aggregation-authorization/"
"{auth_account}/{auth_region}".format( "{auth_account}/{auth_region}".format(
region=current_region, region=current_region,
id=DEFAULT_ACCOUNT_ID, id=get_account_id(),
auth_account=authorized_account_id, auth_account=authorized_account_id,
auth_region=authorized_aws_region, auth_region=authorized_aws_region,
) )
@ -432,7 +432,7 @@ class OrganizationConformancePack(ConfigEmptyDictable):
self.last_update_time = datetime2int(datetime.utcnow()) self.last_update_time = datetime2int(datetime.utcnow())
self.organization_conformance_pack_arn = ( self.organization_conformance_pack_arn = (
"arn:aws:config:{0}:{1}:organization-conformance-pack/{2}".format( "arn:aws:config:{0}:{1}:organization-conformance-pack/{2}".format(
region, DEFAULT_ACCOUNT_ID, self._unique_pack_name region, get_account_id(), self._unique_pack_name
) )
) )
self.organization_conformance_pack_name = name self.organization_conformance_pack_name = name
@ -694,7 +694,7 @@ class ConfigRule(ConfigEmptyDictable):
self.maximum_execution_frequency = None # keeps pylint happy self.maximum_execution_frequency = None # keeps pylint happy
self.modify_fields(region, config_rule, tags) self.modify_fields(region, config_rule, tags)
self.config_rule_id = f"config-rule-{random_string():.6}" self.config_rule_id = f"config-rule-{random_string():.6}"
self.config_rule_arn = f"arn:aws:config:{region}:{DEFAULT_ACCOUNT_ID}:config-rule/{self.config_rule_id}" self.config_rule_arn = f"arn:aws:config:{region}:{get_account_id()}:config-rule/{self.config_rule_id}"
def modify_fields(self, region, config_rule, tags): def modify_fields(self, region, config_rule, tags):
"""Initialize or update ConfigRule fields.""" """Initialize or update ConfigRule fields."""
@ -1436,7 +1436,7 @@ class ConfigBackend(BaseBackend):
resource_identifiers = [] resource_identifiers = []
for identifier in identifiers: for identifier in identifiers:
item = { item = {
"SourceAccountId": DEFAULT_ACCOUNT_ID, "SourceAccountId": get_account_id(),
"SourceRegion": identifier["region"], "SourceRegion": identifier["region"],
"ResourceType": identifier["type"], "ResourceType": identifier["type"],
"ResourceId": identifier["id"], "ResourceId": identifier["id"],
@ -1487,7 +1487,7 @@ class ConfigBackend(BaseBackend):
if not item: if not item:
raise ResourceNotDiscoveredException(resource_type, resource_id) raise ResourceNotDiscoveredException(resource_type, resource_id)
item["accountId"] = DEFAULT_ACCOUNT_ID item["accountId"] = get_account_id()
return {"configurationItems": [item]} return {"configurationItems": [item]}
@ -1533,7 +1533,7 @@ class ConfigBackend(BaseBackend):
if not item: if not item:
continue continue
item["accountId"] = DEFAULT_ACCOUNT_ID item["accountId"] = get_account_id()
results.append(item) results.append(item)
@ -1589,7 +1589,7 @@ class ConfigBackend(BaseBackend):
not_found.append(identifier) not_found.append(identifier)
continue continue
item["accountId"] = DEFAULT_ACCOUNT_ID item["accountId"] = get_account_id()
# The 'tags' field is not included in aggregate results for some reason... # The 'tags' field is not included in aggregate results for some reason...
item.pop("tags", None) item.pop("tags", None)
@ -1728,7 +1728,7 @@ class ConfigBackend(BaseBackend):
# actually here would be a list of all accounts in the organization # actually here would be a list of all accounts in the organization
statuses = [ statuses = [
{ {
"AccountId": DEFAULT_ACCOUNT_ID, "AccountId": get_account_id(),
"ConformancePackName": "OrgConformsPack-{0}".format( "ConformancePackName": "OrgConformsPack-{0}".format(
pack._unique_pack_name pack._unique_pack_name
), ),

View File

@ -1,4 +1,4 @@
from .models import BaseModel, BaseBackend, ACCOUNT_ID # noqa from .models import BaseModel, BaseBackend, get_account_id, ACCOUNT_ID # noqa
from .models import CloudFormationModel, CloudWatchMetricProvider # noqa from .models import CloudFormationModel, CloudWatchMetricProvider # noqa
from .models import patch_client, patch_resource # noqa from .models import patch_client, patch_resource # noqa
from .responses import ActionAuthenticatorMixin from .responses import ActionAuthenticatorMixin

View File

@ -1,5 +1,3 @@
import botocore
import boto3
import functools import functools
import inspect import inspect
import itertools import itertools
@ -7,20 +5,22 @@ import os
import random import random
import re import re
import string import string
import unittest
from abc import abstractmethod from abc import abstractmethod
from io import BytesIO
from collections import defaultdict from collections import defaultdict
from io import BytesIO
from types import FunctionType
from unittest.mock import patch
import boto3
import botocore
import responses
from botocore.awsrequest import AWSResponse
from botocore.config import Config from botocore.config import Config
from botocore.handlers import BUILTIN_HANDLERS from botocore.handlers import BUILTIN_HANDLERS
from botocore.awsrequest import AWSResponse
from types import FunctionType
from moto import settings from moto import settings
from moto.core.exceptions import HTTPException from moto.core.exceptions import HTTPException
import responses
import unittest
from unittest.mock import patch
from .custom_responses_mock import ( from .custom_responses_mock import (
get_response_mock, get_response_mock,
CallbackResponse, CallbackResponse,
@ -29,10 +29,20 @@ from .custom_responses_mock import (
) )
from .utils import convert_regex_to_flask_path, convert_flask_to_responses_response from .utils import convert_regex_to_flask_path, convert_flask_to_responses_response
ACCOUNT_ID = os.environ.get("MOTO_ACCOUNT_ID", "123456789012") ACCOUNT_ID = os.environ.get("MOTO_ACCOUNT_ID", "123456789012")
def _get_default_account_id():
return ACCOUNT_ID
account_id_resolver = _get_default_account_id
def get_account_id():
return account_id_resolver()
class BaseMockAWS: class BaseMockAWS:
nested_count = 0 nested_count = 0
mocks_active = False mocks_active = False
@ -225,7 +235,6 @@ RESPONSES_METHODS = [
responses.PUT, responses.PUT,
] ]
botocore_mock = responses.RequestsMock( botocore_mock = responses.RequestsMock(
assert_all_requests_are_fired=False, assert_all_requests_are_fired=False,
target="botocore.vendored.requests.adapters.HTTPAdapter.send", target="botocore.vendored.requests.adapters.HTTPAdapter.send",
@ -233,7 +242,6 @@ botocore_mock = responses.RequestsMock(
responses_mock = get_response_mock() responses_mock = get_response_mock()
BOTOCORE_HTTP_METHODS = ["GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] BOTOCORE_HTTP_METHODS = ["GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]

View File

@ -411,6 +411,7 @@ def extract_region_from_aws_authorization(string):
class BackendDict(dict): class BackendDict(dict):
def __init__(self, fn, service_name): def __init__(self, fn, service_name):
self.fn = fn self.fn = fn
self.service_name = service_name
sess = Session() sess = Session()
self.regions = list(sess.get_available_regions(service_name)) self.regions = list(sess.get_available_regions(service_name))
self.regions.extend( self.regions.extend(

View File

@ -1,5 +1,5 @@
"""DAXBackend class with methods for supported APIs.""" """DAXBackend class with methods for supported APIs."""
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict, get_random_hex, unix_time from moto.core.utils import BackendDict, get_random_hex, unix_time
from moto.moto_api import state_manager from moto.moto_api import state_manager
from moto.moto_api._internal.managed_state_model import ManagedState from moto.moto_api._internal.managed_state_model import ManagedState
@ -84,7 +84,7 @@ class DaxCluster(BaseModel, ManagedState):
# Set internal properties # Set internal properties
self.name = name self.name = name
self.description = description self.description = description
self.arn = f"arn:aws:dax:{region}:{ACCOUNT_ID}:cache/{self.name}" self.arn = f"arn:aws:dax:{region}:{get_account_id()}:cache/{self.name}"
self.node_type = node_type self.node_type = node_type
self.replication_factor = replication_factor self.replication_factor = replication_factor
self.cluster_hex = get_random_hex(6) self.cluster_hex = get_random_hex(6)

View File

@ -1,7 +1,7 @@
import json import json
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from .exceptions import ( from .exceptions import (
@ -132,7 +132,7 @@ class FakeReplicationTask(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:dms:{region}:{account_id}:task:{task_id}".format( return "arn:aws:dms:{region}:{account_id}:task:{task_id}".format(
region=self.region, account_id=ACCOUNT_ID, task_id=self.id region=self.region, account_id=get_account_id(), task_id=self.id
) )
def to_dict(self): def to_dict(self):

View File

@ -7,7 +7,7 @@ import re
import uuid import uuid
from collections import OrderedDict from collections import OrderedDict
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core import BaseBackend, BaseModel, CloudFormationModel from moto.core import BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import unix_time, unix_time_millis, BackendDict from moto.core.utils import unix_time, unix_time_millis, BackendDict
from moto.core.exceptions import JsonRESTError from moto.core.exceptions import JsonRESTError
@ -562,7 +562,7 @@ class Table(CloudFormationModel):
return table return table
def _generate_arn(self, name): def _generate_arn(self, name):
return f"arn:aws:dynamodb:us-east-1:{ACCOUNT_ID}:table/{name}" return f"arn:aws:dynamodb:us-east-1:{get_account_id()}:table/{name}"
def set_stream_specification(self, streams): def set_stream_specification(self, streams):
self.stream_specification = streams self.stream_specification = streams
@ -1119,7 +1119,7 @@ class Backup(object):
def arn(self): def arn(self):
return "arn:aws:dynamodb:{region}:{account}:table/{table_name}/backup/{identifier}".format( return "arn:aws:dynamodb:{region}:{account}:table/{table_name}/backup/{identifier}".format(
region=self.backend.region_name, region=self.backend.region_name,
account=ACCOUNT_ID, account=get_account_id(),
table_name=self.table.name, table_name=self.table.name,
identifier=self.identifier, identifier=self.identifier,
) )

View File

@ -5,7 +5,7 @@ import json
from collections import OrderedDict from collections import OrderedDict
from moto.core import BaseBackend, BaseModel, CloudFormationModel from moto.core import BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import unix_time from moto.core.utils import unix_time
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from .comparisons import get_comparison_func from .comparisons import get_comparison_func
@ -307,7 +307,7 @@ class Table(CloudFormationModel):
region = "us-east-1" region = "us-east-1"
time = "2000-01-01T00:00:00.000" time = "2000-01-01T00:00:00.000"
return "arn:aws:dynamodb:{0}:{1}:table/{2}/stream/{3}".format( return "arn:aws:dynamodb:{0}:{1}:table/{2}/stream/{3}".format(
region, ACCOUNT_ID, self.name, time region, get_account_id(), self.name, time
) )
raise UnformattedGetAttTemplateException() raise UnformattedGetAttTemplateException()

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core import BaseBackend from moto.core import BaseBackend
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from ..exceptions import ( from ..exceptions import (
@ -54,7 +54,7 @@ from ..utils import (
get_prefix, get_prefix,
) )
OWNER_ID = ACCOUNT_ID OWNER_ID = get_account_id()
def validate_resource_ids(resource_ids): def validate_resource_ids(resource_ids):

View File

@ -1,7 +1,7 @@
import json import json
import re import re
from os import environ from os import environ
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.utilities.utils import load_resource from moto.utilities.utils import load_resource
from ..exceptions import ( from ..exceptions import (
InvalidAMIIdError, InvalidAMIIdError,
@ -34,7 +34,7 @@ class Ami(TaggedEC2Resource):
source_ami=None, source_ami=None,
name=None, name=None,
description=None, description=None,
owner_id=ACCOUNT_ID, owner_id=get_account_id(),
owner_alias=None, owner_alias=None,
public=False, public=False,
virtualization_type=None, virtualization_type=None,
@ -186,7 +186,7 @@ class AmiBackend(object):
source_ami=None, source_ami=None,
name=name, name=name,
description=description, description=description,
owner_id=ACCOUNT_ID, owner_id=get_account_id(),
snapshot_description=f"Created by CreateImage({instance_id}) for {ami_id}", snapshot_description=f"Created by CreateImage({instance_id}) for {ami_id}",
) )
for tag in tags: for tag in tags:
@ -246,7 +246,7 @@ class AmiBackend(object):
# support filtering by Owners=['self'] # support filtering by Owners=['self']
if "self" in owners: if "self" in owners:
owners = list( owners = list(
map(lambda o: ACCOUNT_ID if o == "self" else o, owners) map(lambda o: get_account_id() if o == "self" else o, owners)
) )
images = [ images = [
ami ami

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.utilities.utils import filter_resources from moto.utilities.utils import filter_resources
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
@ -20,7 +20,7 @@ class CarrierGateway(TaggedEC2Resource):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
class CarrierGatewayBackend(object): class CarrierGatewayBackend(object):

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from moto.kms import kms_backends from moto.kms import kms_backends
from moto.packages.boto.ec2.blockdevicemapping import BlockDeviceType from moto.packages.boto.ec2.blockdevicemapping import BlockDeviceType
@ -152,7 +152,7 @@ class Snapshot(TaggedEC2Resource):
volume, volume,
description, description,
encrypted=False, encrypted=False,
owner_id=ACCOUNT_ID, owner_id=get_account_id(),
from_ami=None, from_ami=None,
): ):
self.id = snapshot_id self.id = snapshot_id

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from ..exceptions import InvalidNetworkAttachmentIdError, InvalidNetworkInterfaceIdError from ..exceptions import InvalidNetworkAttachmentIdError, InvalidNetworkInterfaceIdError
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
@ -135,7 +135,7 @@ class NetworkInterface(TaggedEC2Resource, CloudFormationModel):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
@property @property
def association(self): def association(self):

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from ..exceptions import ( from ..exceptions import (
IncorrectStateIamProfileAssociationError, IncorrectStateIamProfileAssociationError,
@ -10,7 +10,7 @@ from ..utils import (
filter_iam_instance_profiles, filter_iam_instance_profiles,
) )
OWNER_ID = ACCOUNT_ID OWNER_ID = get_account_id()
class IamInstanceProfileAssociation(CloudFormationModel): class IamInstanceProfileAssociation(CloudFormationModel):

View File

@ -3,7 +3,7 @@ import warnings
from collections import OrderedDict from collections import OrderedDict
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from moto.core.utils import camelcase_to_underscores from moto.core.utils import camelcase_to_underscores
from moto.packages.boto.ec2.blockdevicemapping import BlockDeviceMapping from moto.packages.boto.ec2.blockdevicemapping import BlockDeviceMapping
@ -59,7 +59,7 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel):
super().__init__() super().__init__()
self.ec2_backend = ec2_backend self.ec2_backend = ec2_backend
self.id = random_instance_id() self.id = random_instance_id()
self.owner_id = ACCOUNT_ID self.owner_id = get_account_id()
self.lifecycle = kwargs.get("lifecycle") self.lifecycle = kwargs.get("lifecycle")
nics = kwargs.get("nics", {}) nics = kwargs.get("nics", {})

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID, CloudFormationModel from moto.core import get_account_id, CloudFormationModel
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
from ..exceptions import ( from ..exceptions import (
@ -81,7 +81,7 @@ class InternetGateway(TaggedEC2Resource, CloudFormationModel):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
@staticmethod @staticmethod
def cloudformation_name_type(): def cloudformation_name_type():

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.utilities.utils import filter_resources from moto.utilities.utils import filter_resources
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
from ..utils import random_managed_prefix_list_id, describe_tag_filter from ..utils import random_managed_prefix_list_id, describe_tag_filter
@ -37,7 +37,9 @@ class ManagedPrefixList(TaggedEC2Resource):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID if not self.resource_owner_id else self.resource_owner_id return (
get_account_id() if not self.resource_owner_id else self.resource_owner_id
)
class ManagedPrefixListBackend(object): class ManagedPrefixListBackend(object):

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from ..exceptions import ( from ..exceptions import (
InvalidNetworkAclIdError, InvalidNetworkAclIdError,
InvalidRouteTableIdError, InvalidRouteTableIdError,
@ -12,7 +12,7 @@ from ..utils import (
) )
OWNER_ID = ACCOUNT_ID OWNER_ID = get_account_id()
class NetworkAclBackend(object): class NetworkAclBackend(object):

View File

@ -1,5 +1,5 @@
import ipaddress import ipaddress
from moto.core import ACCOUNT_ID, CloudFormationModel from moto.core import get_account_id, CloudFormationModel
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
from ..exceptions import ( from ..exceptions import (
DependencyViolationError, DependencyViolationError,
@ -30,7 +30,7 @@ class RouteTable(TaggedEC2Resource, CloudFormationModel):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
@staticmethod @staticmethod
def cloudformation_name_type(): def cloudformation_name_type():

View File

@ -3,7 +3,7 @@ import itertools
import json import json
from collections import defaultdict from collections import defaultdict
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from moto.core.utils import aws_api_matches from moto.core.utils import aws_api_matches
from ..exceptions import ( from ..exceptions import (
@ -70,7 +70,7 @@ class SecurityRule(object):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
def __eq__(self, other): def __eq__(self, other):
if self.ip_protocol != other.ip_protocol: if self.ip_protocol != other.ip_protocol:
@ -127,7 +127,7 @@ class SecurityGroup(TaggedEC2Resource, CloudFormationModel):
self.egress_rules = [] self.egress_rules = []
self.enis = {} self.enis = {}
self.vpc_id = vpc_id self.vpc_id = vpc_id
self.owner_id = ACCOUNT_ID self.owner_id = get_account_id()
self.add_tags(tags or {}) self.add_tags(tags or {})
self.is_default = is_default or False self.is_default = is_default or False
@ -1011,7 +1011,7 @@ class SecurityGroupBackend(object):
_source_groups = [] _source_groups = []
for item in source_groups or []: for item in source_groups or []:
if "OwnerId" not in item: if "OwnerId" not in item:
item["OwnerId"] = ACCOUNT_ID item["OwnerId"] = get_account_id()
# for VPCs # for VPCs
if "GroupId" in item: if "GroupId" in item:
if not self.get_security_group_by_name_or_id( if not self.get_security_group_by_name_or_id(

View File

@ -2,7 +2,7 @@ import ipaddress
import itertools import itertools
from collections import defaultdict from collections import defaultdict
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from ..exceptions import ( from ..exceptions import (
GenericInvalidParameterValueError, GenericInvalidParameterValueError,
@ -61,7 +61,7 @@ class Subnet(TaggedEC2Resource, CloudFormationModel):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
@staticmethod @staticmethod
def cloudformation_name_type(): def cloudformation_name_type():

View File

@ -1,5 +1,5 @@
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID, CloudFormationModel from moto.core import get_account_id, CloudFormationModel
from moto.core.utils import iso_8601_datetime_with_milliseconds from moto.core.utils import iso_8601_datetime_with_milliseconds
from moto.utilities.utils import filter_resources, merge_multiple_dicts from moto.utilities.utils import filter_resources, merge_multiple_dicts
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
@ -38,7 +38,7 @@ class TransitGateway(TaggedEC2Resource, CloudFormationModel):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
@staticmethod @staticmethod
def cloudformation_name_type(): def cloudformation_name_type():

View File

@ -1,5 +1,5 @@
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.utils import iso_8601_datetime_with_milliseconds from moto.core.utils import iso_8601_datetime_with_milliseconds
from moto.utilities.utils import merge_multiple_dicts, filter_resources from moto.utilities.utils import merge_multiple_dicts, filter_resources
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
@ -32,11 +32,11 @@ class TransitGatewayAttachment(TaggedEC2Resource):
@property @property
def resource_owner_id(self): def resource_owner_id(self):
return ACCOUNT_ID return get_account_id()
@property @property
def transit_gateway_owner_id(self): def transit_gateway_owner_id(self):
return ACCOUNT_ID return get_account_id()
class TransitGatewayVpcAttachment(TransitGatewayAttachment): class TransitGatewayVpcAttachment(TransitGatewayAttachment):
@ -95,7 +95,7 @@ class TransitGatewayPeeringAttachment(TransitGatewayAttachment):
@property @property
def resource_owner_id(self): def resource_owner_id(self):
return ACCOUNT_ID return get_account_id()
class TransitGatewayAttachmentBackend(object): class TransitGatewayAttachmentBackend(object):

View File

@ -4,7 +4,7 @@ import weakref
from collections import defaultdict from collections import defaultdict
from operator import itemgetter from operator import itemgetter
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from .core import TaggedEC2Resource from .core import TaggedEC2Resource
from ..exceptions import ( from ..exceptions import (
@ -78,7 +78,7 @@ class VPCEndPoint(TaggedEC2Resource, CloudFormationModel):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
@property @property
def physical_resource_id(self): def physical_resource_id(self):
@ -158,7 +158,7 @@ class VPC(TaggedEC2Resource, CloudFormationModel):
@property @property
def owner_id(self): def owner_id(self):
return ACCOUNT_ID return get_account_id()
@staticmethod @staticmethod
def cloudformation_name_type(): def cloudformation_name_type():

View File

@ -4,7 +4,7 @@ from moto.ec2.exceptions import (
InvalidParameterCombination, InvalidParameterCombination,
InvalidRequest, InvalidRequest,
) )
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from copy import deepcopy from copy import deepcopy
@ -384,7 +384,7 @@ EC2_RUN_INSTANCES = (
<requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId> <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
<reservationId>{{ reservation.id }}</reservationId> <reservationId>{{ reservation.id }}</reservationId>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<groupSet> <groupSet>
<item> <item>
@ -471,7 +471,7 @@ EC2_RUN_INSTANCES = (
{% endif %} {% endif %}
<description>Primary network interface</description> <description>Primary network interface</description>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<status>in-use</status> <status>in-use</status>
<macAddress>1b:2b:3c:4d:5e:6f</macAddress> <macAddress>1b:2b:3c:4d:5e:6f</macAddress>
@ -496,7 +496,7 @@ EC2_RUN_INSTANCES = (
<association> <association>
<publicIp>{{ nic.public_ip }}</publicIp> <publicIp>{{ nic.public_ip }}</publicIp>
<ipOwnerId>""" <ipOwnerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ipOwnerId> + """</ipOwnerId>
</association> </association>
{% endif %} {% endif %}
@ -508,7 +508,7 @@ EC2_RUN_INSTANCES = (
<association> <association>
<publicIp>{{ nic.public_ip }}</publicIp> <publicIp>{{ nic.public_ip }}</publicIp>
<ipOwnerId>""" <ipOwnerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ipOwnerId> + """</ipOwnerId>
</association> </association>
{% endif %} {% endif %}
@ -531,7 +531,7 @@ EC2_DESCRIBE_INSTANCES = (
<item> <item>
<reservationId>{{ reservation.id }}</reservationId> <reservationId>{{ reservation.id }}</reservationId>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<groupSet> <groupSet>
{% for group in reservation.dynamic_group_list %} {% for group in reservation.dynamic_group_list %}
@ -629,7 +629,7 @@ EC2_DESCRIBE_INSTANCES = (
</blockDeviceMapping> </blockDeviceMapping>
<virtualizationType>{{ instance.virtualization_type }}</virtualizationType> <virtualizationType>{{ instance.virtualization_type }}</virtualizationType>
<clientToken>ABCDE""" <clientToken>ABCDE"""
+ ACCOUNT_ID + get_account_id()
+ """3</clientToken> + """3</clientToken>
{% if instance.get_tags() %} {% if instance.get_tags() %}
<tagSet> <tagSet>
@ -654,7 +654,7 @@ EC2_DESCRIBE_INSTANCES = (
{% endif %} {% endif %}
<description>Primary network interface</description> <description>Primary network interface</description>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<status>in-use</status> <status>in-use</status>
<macAddress>1b:2b:3c:4d:5e:6f</macAddress> <macAddress>1b:2b:3c:4d:5e:6f</macAddress>
@ -683,7 +683,7 @@ EC2_DESCRIBE_INSTANCES = (
<association> <association>
<publicIp>{{ nic.public_ip }}</publicIp> <publicIp>{{ nic.public_ip }}</publicIp>
<ipOwnerId>""" <ipOwnerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ipOwnerId> + """</ipOwnerId>
</association> </association>
{% endif %} {% endif %}
@ -695,7 +695,7 @@ EC2_DESCRIBE_INSTANCES = (
<association> <association>
<publicIp>{{ nic.public_ip }}</publicIp> <publicIp>{{ nic.public_ip }}</publicIp>
<ipOwnerId>""" <ipOwnerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ipOwnerId> + """</ipOwnerId>
</association> </association>
{% endif %} {% endif %}

View File

@ -1,5 +1,5 @@
from moto.core.responses import BaseResponse from moto.core.responses import BaseResponse
from moto.core import ACCOUNT_ID from moto.core import get_account_id
class VPCPeeringConnections(BaseResponse): class VPCPeeringConnections(BaseResponse):
@ -74,7 +74,7 @@ CREATE_VPC_PEERING_CONNECTION_RESPONSE = (
<vpcPeeringConnectionId>{{ vpc_pcx.id }}</vpcPeeringConnectionId> <vpcPeeringConnectionId>{{ vpc_pcx.id }}</vpcPeeringConnectionId>
<requesterVpcInfo> <requesterVpcInfo>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<vpcId>{{ vpc_pcx.vpc.id }}</vpcId> <vpcId>{{ vpc_pcx.vpc.id }}</vpcId>
<cidrBlock>{{ vpc_pcx.vpc.cidr_block }}</cidrBlock> <cidrBlock>{{ vpc_pcx.vpc.cidr_block }}</cidrBlock>
@ -86,7 +86,7 @@ CREATE_VPC_PEERING_CONNECTION_RESPONSE = (
</requesterVpcInfo> </requesterVpcInfo>
<accepterVpcInfo> <accepterVpcInfo>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<vpcId>{{ vpc_pcx.peer_vpc.id }}</vpcId> <vpcId>{{ vpc_pcx.peer_vpc.id }}</vpcId>
<peeringOptions> <peeringOptions>
@ -123,7 +123,7 @@ DESCRIBE_VPC_PEERING_CONNECTIONS_RESPONSE = (
<vpcPeeringConnectionId>{{ vpc_pcx.id }}</vpcPeeringConnectionId> <vpcPeeringConnectionId>{{ vpc_pcx.id }}</vpcPeeringConnectionId>
<requesterVpcInfo> <requesterVpcInfo>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<vpcId>{{ vpc_pcx.vpc.id }}</vpcId> <vpcId>{{ vpc_pcx.vpc.id }}</vpcId>
<cidrBlock>{{ vpc_pcx.vpc.cidr_block }}</cidrBlock> <cidrBlock>{{ vpc_pcx.vpc.cidr_block }}</cidrBlock>
@ -136,7 +136,7 @@ DESCRIBE_VPC_PEERING_CONNECTIONS_RESPONSE = (
</requesterVpcInfo> </requesterVpcInfo>
<accepterVpcInfo> <accepterVpcInfo>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<vpcId>{{ vpc_pcx.peer_vpc.id }}</vpcId> <vpcId>{{ vpc_pcx.peer_vpc.id }}</vpcId>
<cidrBlock>{{ vpc_pcx.peer_vpc.cidr_block }}</cidrBlock> <cidrBlock>{{ vpc_pcx.peer_vpc.cidr_block }}</cidrBlock>
@ -181,7 +181,7 @@ ACCEPT_VPC_PEERING_CONNECTION_RESPONSE = (
<vpcPeeringConnectionId>{{ vpc_pcx.id }}</vpcPeeringConnectionId> <vpcPeeringConnectionId>{{ vpc_pcx.id }}</vpcPeeringConnectionId>
<requesterVpcInfo> <requesterVpcInfo>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<vpcId>{{ vpc_pcx.vpc.id }}</vpcId> <vpcId>{{ vpc_pcx.vpc.id }}</vpcId>
<cidrBlock>{{ vpc_pcx.vpc.cidr_block }}</cidrBlock> <cidrBlock>{{ vpc_pcx.vpc.cidr_block }}</cidrBlock>
@ -189,7 +189,7 @@ ACCEPT_VPC_PEERING_CONNECTION_RESPONSE = (
</requesterVpcInfo> </requesterVpcInfo>
<accepterVpcInfo> <accepterVpcInfo>
<ownerId>""" <ownerId>"""
+ ACCOUNT_ID + get_account_id()
+ """</ownerId> + """</ownerId>
<vpcId>{{ vpc_pcx.peer_vpc.id }}</vpcId> <vpcId>{{ vpc_pcx.peer_vpc.id }}</vpcId>
<cidrBlock>{{ vpc_pcx.peer_vpc.cidr_block }}</cidrBlock> <cidrBlock>{{ vpc_pcx.peer_vpc.cidr_block }}</cidrBlock>

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.utils import camelcase_to_underscores from moto.core.utils import camelcase_to_underscores
from moto.ec2.utils import add_tag_specification from moto.ec2.utils import add_tag_specification
from ._base_response import EC2BaseResponse from ._base_response import EC2BaseResponse
@ -224,7 +224,9 @@ class VPCs(EC2BaseResponse):
vpc_end_point_ids=vpc_end_points_ids, filters=filters vpc_end_point_ids=vpc_end_points_ids, filters=filters
) )
template = self.response_template(DESCRIBE_VPC_ENDPOINT_RESPONSE) template = self.response_template(DESCRIBE_VPC_ENDPOINT_RESPONSE)
return template.render(vpc_end_points=vpc_end_points, account_id=ACCOUNT_ID) return template.render(
vpc_end_points=vpc_end_points, account_id=get_account_id()
)
def delete_vpc_endpoints(self): def delete_vpc_endpoints(self):
vpc_end_points_ids = self._get_multi_param("VpcEndpointId") vpc_end_points_ids = self._get_multi_param("VpcEndpointId")

View File

@ -10,7 +10,7 @@ from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.asymmetric import rsa
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.iam import iam_backends from moto.iam import iam_backends
EC2_RESOURCE_TO_PREFIX = { EC2_RESOURCE_TO_PREFIX = {
@ -326,7 +326,7 @@ def get_object_value(obj, attr):
val = obj val = obj
for key in keys: for key in keys:
if key == "owner_id": if key == "owner_id":
return ACCOUNT_ID return get_account_id()
elif hasattr(val, key): elif hasattr(val, key):
val = getattr(val, key) val = getattr(val, key)
elif isinstance(val, dict): elif isinstance(val, dict):

View File

@ -9,7 +9,7 @@ from typing import Dict, List
from botocore.exceptions import ParamValidationError from botocore.exceptions import ParamValidationError
from moto.core import BaseBackend, BaseModel, CloudFormationModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, CloudFormationModel, get_account_id
from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict
from moto.ecr.exceptions import ( from moto.ecr.exceptions import (
ImageNotFoundException, ImageNotFoundException,
@ -29,7 +29,7 @@ from moto.iam.exceptions import MalformedPolicyDocument
from moto.iam.policy_validation import IAMPolicyDocumentValidator from moto.iam.policy_validation import IAMPolicyDocumentValidator
from moto.utilities.tagging_service import TaggingService from moto.utilities.tagging_service import TaggingService
DEFAULT_REGISTRY_ID = ACCOUNT_ID DEFAULT_REGISTRY_ID = get_account_id()
ECR_REPOSITORY_ARN_PATTERN = "^arn:(?P<partition>[^:]+):ecr:(?P<region>[^:]+):(?P<account_id>[^:]+):repository/(?P<repo_name>.*)$" ECR_REPOSITORY_ARN_PATTERN = "^arn:(?P<partition>[^:]+):ecr:(?P<region>[^:]+):(?P<account_id>[^:]+):repository/(?P<repo_name>.*)$"
EcrRepositoryArn = namedtuple( EcrRepositoryArn = namedtuple(
@ -96,7 +96,7 @@ class Repository(BaseObject, CloudFormationModel):
if encryption_config == {"encryptionType": "KMS"}: if encryption_config == {"encryptionType": "KMS"}:
encryption_config[ encryption_config[
"kmsKey" "kmsKey"
] = f"arn:aws:kms:{self.region_name}:{ACCOUNT_ID}:key/{uuid.uuid4()}" ] = f"arn:aws:kms:{self.region_name}:{get_account_id()}:key/{uuid.uuid4()}"
return encryption_config return encryption_config
def _get_image(self, image_tag, image_digest): def _get_image(self, image_tag, image_digest):
@ -824,28 +824,28 @@ class ECRBackend(BaseBackend):
self.registry_policy = policy_text self.registry_policy = policy_text
return { return {
"registryId": ACCOUNT_ID, "registryId": get_account_id(),
"policyText": policy_text, "policyText": policy_text,
} }
def get_registry_policy(self): def get_registry_policy(self):
if not self.registry_policy: if not self.registry_policy:
raise RegistryPolicyNotFoundException(ACCOUNT_ID) raise RegistryPolicyNotFoundException(get_account_id())
return { return {
"registryId": ACCOUNT_ID, "registryId": get_account_id(),
"policyText": self.registry_policy, "policyText": self.registry_policy,
} }
def delete_registry_policy(self): def delete_registry_policy(self):
policy = self.registry_policy policy = self.registry_policy
if not policy: if not policy:
raise RegistryPolicyNotFoundException(ACCOUNT_ID) raise RegistryPolicyNotFoundException(get_account_id())
self.registry_policy = None self.registry_policy = None
return { return {
"registryId": ACCOUNT_ID, "registryId": get_account_id(),
"policyText": policy, "policyText": policy,
} }

View File

@ -7,7 +7,7 @@ from random import random, randint
import pytz import pytz
from moto import settings from moto import settings
from moto.core import BaseBackend, BaseModel, CloudFormationModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, CloudFormationModel, get_account_id
from moto.core.exceptions import JsonRESTError from moto.core.exceptions import JsonRESTError
from moto.core.utils import ( from moto.core.utils import (
unix_time, unix_time,
@ -64,7 +64,7 @@ class Cluster(BaseObject, CloudFormationModel):
def __init__(self, cluster_name, region_name, cluster_settings=None): def __init__(self, cluster_name, region_name, cluster_settings=None):
self.active_services_count = 0 self.active_services_count = 0
self.arn = "arn:aws:ecs:{0}:{1}:cluster/{2}".format( self.arn = "arn:aws:ecs:{0}:{1}:cluster/{2}".format(
region_name, ACCOUNT_ID, cluster_name region_name, get_account_id(), cluster_name
) )
self.name = cluster_name self.name = cluster_name
self.pending_tasks_count = 0 self.pending_tasks_count = 0
@ -154,7 +154,7 @@ class TaskDefinition(BaseObject, CloudFormationModel):
self.family = family self.family = family
self.revision = revision self.revision = revision
self.arn = "arn:aws:ecs:{0}:{1}:task-definition/{2}:{3}".format( self.arn = "arn:aws:ecs:{0}:{1}:task-definition/{2}:{3}".format(
region_name, ACCOUNT_ID, family, revision region_name, get_account_id(), family, revision
) )
default_container_definition = { default_container_definition = {
@ -315,9 +315,9 @@ class Task(BaseObject):
@property @property
def task_arn(self): def task_arn(self):
if self._backend.enable_long_arn_for_name(name="taskLongArnFormat"): if self._backend.enable_long_arn_for_name(name="taskLongArnFormat"):
return f"arn:aws:ecs:{self.region_name}:{ACCOUNT_ID}:task/{self.cluster_name}/{self.id}" return f"arn:aws:ecs:{self.region_name}:{get_account_id()}:task/{self.cluster_name}/{self.id}"
return "arn:aws:ecs:{0}:{1}:task/{2}".format( return "arn:aws:ecs:{0}:{1}:task/{2}".format(
self.region_name, ACCOUNT_ID, self.id self.region_name, get_account_id(), self.id
) )
@property @property
@ -330,7 +330,7 @@ class Task(BaseObject):
class CapacityProvider(BaseObject): class CapacityProvider(BaseObject):
def __init__(self, region_name, name, asg_details, tags): def __init__(self, region_name, name, asg_details, tags):
self._id = str(uuid.uuid4()) self._id = str(uuid.uuid4())
self.capacity_provider_arn = f"arn:aws:ecs:{region_name}:{ACCOUNT_ID}:capacity_provider/{name}/{self._id}" self.capacity_provider_arn = f"arn:aws:ecs:{region_name}:{get_account_id()}:capacity_provider/{name}/{self._id}"
self.name = name self.name = name
self.status = "ACTIVE" self.status = "ACTIVE"
self.auto_scaling_group_provider = asg_details self.auto_scaling_group_provider = asg_details
@ -341,7 +341,7 @@ class CapacityProviderFailure(BaseObject):
def __init__(self, reason, name, region_name): def __init__(self, reason, name, region_name):
self.reason = reason self.reason = reason
self.arn = "arn:aws:ecs:{0}:{1}:capacity_provider/{2}".format( self.arn = "arn:aws:ecs:{0}:{1}:capacity_provider/{2}".format(
region_name, ACCOUNT_ID, name region_name, get_account_id(), name
) )
@property @property
@ -410,9 +410,9 @@ class Service(BaseObject, CloudFormationModel):
@property @property
def arn(self): def arn(self):
if self._backend.enable_long_arn_for_name(name="serviceLongArnFormat"): if self._backend.enable_long_arn_for_name(name="serviceLongArnFormat"):
return f"arn:aws:ecs:{self.region_name}:{ACCOUNT_ID}:service/{self.cluster_name}/{self.name}" return f"arn:aws:ecs:{self.region_name}:{get_account_id()}:service/{self.cluster_name}/{self.name}"
return "arn:aws:ecs:{0}:{1}:service/{2}".format( return "arn:aws:ecs:{0}:{1}:service/{2}".format(
self.region_name, ACCOUNT_ID, self.name self.region_name, get_account_id(), self.name
) )
@property @property
@ -618,10 +618,8 @@ class ContainerInstance(BaseObject):
if self._backend.enable_long_arn_for_name( if self._backend.enable_long_arn_for_name(
name="containerInstanceLongArnFormat" name="containerInstanceLongArnFormat"
): ):
return f"arn:aws:ecs:{self.region_name}:{ACCOUNT_ID}:container-instance/{self.cluster_name}/{self.id}" return f"arn:aws:ecs:{self.region_name}:{get_account_id()}:container-instance/{self.cluster_name}/{self.id}"
return ( return f"arn:aws:ecs:{self.region_name}:{get_account_id()}:container-instance/{self.id}"
f"arn:aws:ecs:{self.region_name}:{ACCOUNT_ID}:container-instance/{self.id}"
)
@property @property
def response_object(self): def response_object(self):
@ -648,7 +646,7 @@ class ClusterFailure(BaseObject):
def __init__(self, reason, cluster_name, region_name): def __init__(self, reason, cluster_name, region_name):
self.reason = reason self.reason = reason
self.arn = "arn:aws:ecs:{0}:{1}:cluster/{2}".format( self.arn = "arn:aws:ecs:{0}:{1}:cluster/{2}".format(
region_name, ACCOUNT_ID, cluster_name region_name, get_account_id(), cluster_name
) )
@property @property
@ -663,7 +661,7 @@ class ContainerInstanceFailure(BaseObject):
def __init__(self, reason, container_instance_id, region_name): def __init__(self, reason, container_instance_id, region_name):
self.reason = reason self.reason = reason
self.arn = "arn:aws:ecs:{0}:{1}:container-instance/{2}".format( self.arn = "arn:aws:ecs:{0}:{1}:container-instance/{2}".format(
region_name, ACCOUNT_ID, container_instance_id region_name, get_account_id(), container_instance_id
) )
@property @property
@ -718,7 +716,7 @@ class TaskSet(BaseObject):
cluster_name = self.cluster.split("/")[-1] cluster_name = self.cluster.split("/")[-1]
service_name = self.service.split("/")[-1] service_name = self.service.split("/")[-1]
self.task_set_arn = "arn:aws:ecs:{0}:{1}:task-set/{2}/{3}/{4}".format( self.task_set_arn = "arn:aws:ecs:{0}:{1}:task-set/{2}/{3}/{4}".format(
region_name, ACCOUNT_ID, cluster_name, service_name, self.id region_name, get_account_id(), cluster_name, service_name, self.id
) )
@property @property
@ -1305,7 +1303,7 @@ class EC2ContainerServiceBackend(BaseBackend):
result.append(self.services[cluster_service_pair]) result.append(self.services[cluster_service_pair])
else: else:
missing_arn = ( missing_arn = (
f"arn:aws:ecs:{self.region_name}:{ACCOUNT_ID}:service/{name}" f"arn:aws:ecs:{self.region_name}:{get_account_id()}:service/{name}"
) )
failures.append({"arn": missing_arn, "reason": "MISSING"}) failures.append({"arn": missing_arn, "reason": "MISSING"})

View File

@ -9,7 +9,7 @@ import time
from copy import deepcopy from copy import deepcopy
from hashlib import md5 from hashlib import md5
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel, CloudFormationModel from moto.core import get_account_id, BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import ( from moto.core.utils import (
camelcase_to_underscores, camelcase_to_underscores,
get_random_hex, get_random_hex,
@ -55,7 +55,9 @@ class AccessPoint(BaseModel):
): ):
self.access_point_id = get_random_hex(8) self.access_point_id = get_random_hex(8)
self.access_point_arn = "arn:aws:elasticfilesystem:{region}:{user_id}:access-point/fsap-{file_system_id}".format( self.access_point_arn = "arn:aws:elasticfilesystem:{region}:{user_id}:access-point/fsap-{file_system_id}".format(
region=region_name, user_id=ACCOUNT_ID, file_system_id=self.access_point_id region=region_name,
user_id=get_account_id(),
file_system_id=self.access_point_id,
) )
self.client_token = client_token self.client_token = client_token
self.file_system_id = file_system_id self.file_system_id = file_system_id
@ -79,7 +81,7 @@ class AccessPoint(BaseModel):
"FileSystemId": self.file_system_id, "FileSystemId": self.file_system_id,
"PosixUser": self.posix_user, "PosixUser": self.posix_user,
"RootDirectory": self.root_directory, "RootDirectory": self.root_directory,
"OwnerId": ACCOUNT_ID, "OwnerId": get_account_id(),
"LifeCycleState": "available", "LifeCycleState": "available",
} }
@ -128,10 +130,12 @@ class FileSystem(CloudFormationModel):
# Generate AWS-assigned parameters # Generate AWS-assigned parameters
self.file_system_id = file_system_id self.file_system_id = file_system_id
self.file_system_arn = "arn:aws:elasticfilesystem:{region}:{user_id}:file-system/{file_system_id}".format( self.file_system_arn = "arn:aws:elasticfilesystem:{region}:{user_id}:file-system/{file_system_id}".format(
region=region_name, user_id=ACCOUNT_ID, file_system_id=self.file_system_id region=region_name,
user_id=get_account_id(),
file_system_id=self.file_system_id,
) )
self.creation_time = time.time() self.creation_time = time.time()
self.owner_id = ACCOUNT_ID self.owner_id = get_account_id()
# Initialize some state parameters # Initialize some state parameters
self.life_cycle_state = "available" self.life_cycle_state = "available"
@ -288,7 +292,7 @@ class MountTarget(CloudFormationModel):
self.ip_address = ip_address self.ip_address = ip_address
# Init non-user-assigned values. # Init non-user-assigned values.
self.owner_id = ACCOUNT_ID self.owner_id = get_account_id()
self.mount_target_id = "fsmt-{}".format(get_random_hex()) self.mount_target_id = "fsmt-{}".format(get_random_hex())
self.life_cycle_state = "available" self.life_cycle_state = "available"
self.network_interface_id = None self.network_interface_id = None

View File

@ -1,7 +1,7 @@
from datetime import datetime from datetime import datetime
from uuid import uuid4 from uuid import uuid4
from moto.core import ACCOUNT_ID, BaseBackend from moto.core import get_account_id, BaseBackend
from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict
from ..utilities.utils import random_string from ..utilities.utils import random_string
@ -15,16 +15,16 @@ from .utils import get_partition, validate_role_arn
# String Templates # String Templates
CLUSTER_ARN_TEMPLATE = ( CLUSTER_ARN_TEMPLATE = (
"arn:{partition}:eks:{region}:" + str(ACCOUNT_ID) + ":cluster/{name}" "arn:{partition}:eks:{region}:" + str(get_account_id()) + ":cluster/{name}"
) )
FARGATE_PROFILE_ARN_TEMPLATE = ( FARGATE_PROFILE_ARN_TEMPLATE = (
"arn:{partition}:eks:{region}:" "arn:{partition}:eks:{region}:"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":fargateprofile/{cluster_name}/{fargate_profile_name}/{uuid}" + ":fargateprofile/{cluster_name}/{fargate_profile_name}/{uuid}"
) )
NODEGROUP_ARN_TEMPLATE = ( NODEGROUP_ARN_TEMPLATE = (
"arn:{partition}:eks:{region}:" "arn:{partition}:eks:{region}:"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":nodegroup/{cluster_name}/{nodegroup_name}/{uuid}" + ":nodegroup/{cluster_name}/{nodegroup_name}/{uuid}"
) )
ISSUER_TEMPLATE = "https://oidc.eks.{region}.amazonaws.com/id/" + random_string(10) ISSUER_TEMPLATE = "https://oidc.eks.{region}.amazonaws.com/id/" + random_string(10)

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from .exceptions import UserAlreadyExists, UserNotFound from .exceptions import UserAlreadyExists, UserNotFound
@ -28,7 +28,7 @@ class User(BaseModel):
@property @property
def arn(self): def arn(self):
return f"arn:aws:elasticache:{self.region}:{ACCOUNT_ID}:user:{self.id}" return f"arn:aws:elasticache:{self.region}:{get_account_id()}:user:{self.id}"
class ElastiCacheBackend(BaseBackend): class ElastiCacheBackend(BaseBackend):

View File

@ -1,6 +1,6 @@
import weakref import weakref
from moto.core import BaseBackend, BaseModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, get_account_id
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from .exceptions import InvalidParameterValueError, ResourceNotFoundException from .exceptions import InvalidParameterValueError, ResourceNotFoundException
from .utils import make_arn from .utils import make_arn
@ -22,7 +22,7 @@ class FakeEnvironment(BaseModel):
@property @property
def environment_arn(self): def environment_arn(self):
resource_path = "%s/%s" % (self.application_name, self.environment_name) resource_path = "%s/%s" % (self.application_name, self.environment_name)
return make_arn(self.region, ACCOUNT_ID, "environment", resource_path) return make_arn(self.region, get_account_id(), "environment", resource_path)
@property @property
def platform_arn(self): def platform_arn(self):
@ -59,7 +59,9 @@ class FakeApplication(BaseModel):
@property @property
def arn(self): def arn(self):
return make_arn(self.region, ACCOUNT_ID, "application", self.application_name) return make_arn(
self.region, get_account_id(), "application", self.application_name
)
class EBBackend(BaseBackend): class EBBackend(BaseBackend):

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
import random import random
import string import string
@ -20,7 +20,7 @@ class Pipeline(BaseModel):
self.id = "{}-{}".format(a, b) self.id = "{}-{}".format(a, b)
self.name = name self.name = name
self.arn = "arn:aws:elastictranscoder:{}:{}:pipeline/{}".format( self.arn = "arn:aws:elastictranscoder:{}:{}:pipeline/{}".format(
region, ACCOUNT_ID, self.id region, get_account_id(), self.id
) )
self.status = "Active" self.status = "Active"
self.input_bucket = input_bucket self.input_bucket = input_bucket

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.responses import BaseResponse from moto.core.responses import BaseResponse
from .models import elastictranscoder_backends from .models import elastictranscoder_backends
import json import json
@ -84,7 +84,7 @@ class ElasticTranscoderResponse(BaseResponse):
return None return None
except KeyError: except KeyError:
msg = "The specified pipeline was not found: account={}, pipelineId={}.".format( msg = "The specified pipeline was not found: account={}, pipelineId={}.".format(
ACCOUNT_ID, pipeline_id get_account_id(), pipeline_id
) )
return ( return (
404, 404,

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.responses import BaseResponse from moto.core.responses import BaseResponse
from .models import elb_backends from .models import elb_backends
from .exceptions import DuplicateTagKeysError, LoadBalancerNotFoundError from .exceptions import DuplicateTagKeysError, LoadBalancerNotFoundError
@ -59,7 +59,7 @@ class ELBResponse(BaseResponse):
template = self.response_template(DESCRIBE_LOAD_BALANCERS_TEMPLATE) template = self.response_template(DESCRIBE_LOAD_BALANCERS_TEMPLATE)
return template.render( return template.render(
ACCOUNT_ID=ACCOUNT_ID, ACCOUNT_ID=get_account_id(),
load_balancers=load_balancers_resp, load_balancers=load_balancers_resp,
marker=next_marker, marker=next_marker,
) )

View File

@ -4,7 +4,7 @@ from jinja2 import Template
from botocore.exceptions import ParamValidationError from botocore.exceptions import ParamValidationError
from collections import OrderedDict from collections import OrderedDict
from moto.core.exceptions import RESTError from moto.core.exceptions import RESTError
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel, CloudFormationModel from moto.core import get_account_id, BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import ( from moto.core.utils import (
iso_8601_datetime_with_milliseconds, iso_8601_datetime_with_milliseconds,
get_random_hex, get_random_hex,
@ -694,7 +694,7 @@ class ELBv2Backend(BaseBackend):
vpc_id = subnets[0].vpc_id vpc_id = subnets[0].vpc_id
arn = make_arn_for_load_balancer( arn = make_arn_for_load_balancer(
account_id=ACCOUNT_ID, name=name, region_name=self.region_name account_id=get_account_id(), name=name, region_name=self.region_name
) )
dns_name = "%s-1.%s.elb.amazonaws.com" % (name, self.region_name) dns_name = "%s-1.%s.elb.amazonaws.com" % (name, self.region_name)
@ -1022,7 +1022,7 @@ Member must satisfy regular expression pattern: {}".format(
) )
arn = make_arn_for_target_group( arn = make_arn_for_target_group(
account_id=ACCOUNT_ID, name=name, region_name=self.region_name account_id=get_account_id(), name=name, region_name=self.region_name
) )
tags = kwargs.pop("tags", None) tags = kwargs.pop("tags", None)
target_group = FakeTargetGroup(name, arn, **kwargs) target_group = FakeTargetGroup(name, arn, **kwargs)

View File

@ -5,7 +5,7 @@ import warnings
import pytz import pytz
from dateutil.parser import parse as dtparse from dateutil.parser import parse as dtparse
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.emr.exceptions import ( from moto.emr.exceptions import (
InvalidRequestException, InvalidRequestException,
@ -280,7 +280,7 @@ class FakeCluster(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:elasticmapreduce:{0}:{1}:cluster/{2}".format( return "arn:aws:elasticmapreduce:{0}:{1}:cluster/{2}".format(
self.emr_backend.region_name, ACCOUNT_ID, self.id self.emr_backend.region_name, get_account_id(), self.id
) )
@property @property

View File

@ -2,7 +2,7 @@
import re import re
from datetime import datetime from datetime import datetime
from moto.core import BaseBackend, BaseModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, get_account_id
from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict
from .utils import random_cluster_id, random_job_id, get_partition, paginated_list from .utils import random_cluster_id, random_job_id, get_partition, paginated_list
@ -12,13 +12,13 @@ from ..config.exceptions import ValidationException
VIRTUAL_CLUSTER_ARN_TEMPLATE = ( VIRTUAL_CLUSTER_ARN_TEMPLATE = (
"arn:{partition}:emr-containers:{region}:" "arn:{partition}:emr-containers:{region}:"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":/virtualclusters/{virtual_cluster_id}" + ":/virtualclusters/{virtual_cluster_id}"
) )
JOB_ARN_TEMPLATE = ( JOB_ARN_TEMPLATE = (
"arn:{partition}:emr-containers:{region}:" "arn:{partition}:emr-containers:{region}:"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":/virtualclusters/{virtual_cluster_id}/jobruns/{job_id}" + ":/virtualclusters/{virtual_cluster_id}/jobruns/{job_id}"
) )

View File

@ -12,7 +12,7 @@ from operator import lt, le, eq, ge, gt
from collections import OrderedDict from collections import OrderedDict
from moto.core.exceptions import JsonRESTError from moto.core.exceptions import JsonRESTError
from moto.core import ACCOUNT_ID, BaseBackend, CloudFormationModel, BaseModel from moto.core import get_account_id, BaseBackend, CloudFormationModel, BaseModel
from moto.core.utils import ( from moto.core.utils import (
unix_time, unix_time,
unix_time_millis, unix_time_millis,
@ -59,7 +59,7 @@ class Rule(CloudFormationModel):
self.event_bus_name = event_bus_name self.event_bus_name = event_bus_name
self.state = state or "ENABLED" self.state = state or "ENABLED"
self.managed_by = managed_by # can only be set by AWS services self.managed_by = managed_by # can only be set by AWS services
self.created_by = ACCOUNT_ID self.created_by = get_account_id()
self.targets = targets or [] self.targets = targets or []
@property @property
@ -73,7 +73,7 @@ class Rule(CloudFormationModel):
return ( return (
"arn:aws:events:{region}:{account_id}:rule/{event_bus_name}{name}".format( "arn:aws:events:{region}:{account_id}:rule/{event_bus_name}{name}".format(
region=self.region_name, region=self.region_name,
account_id=ACCOUNT_ID, account_id=get_account_id(),
event_bus_name=event_bus_name, event_bus_name=event_bus_name,
name=self.name, name=self.name,
) )
@ -321,7 +321,7 @@ class EventBus(CloudFormationModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:events:{region}:{account_id}:event-bus/{name}".format( return "arn:aws:events:{region}:{account_id}:event-bus/{name}".format(
region=self.region, account_id=ACCOUNT_ID, name=self.name region=self.region, account_id=get_account_id(), name=self.name
) )
@property @property
@ -507,7 +507,7 @@ class Archive(CloudFormationModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:events:{region}:{account_id}:archive/{name}".format( return "arn:aws:events:{region}:{account_id}:archive/{name}".format(
region=self.region, account_id=ACCOUNT_ID, name=self.name region=self.region, account_id=get_account_id(), name=self.name
) )
def describe_short(self): def describe_short(self):
@ -640,7 +640,7 @@ class Replay(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:events:{region}:{account_id}:replay/{name}".format( return "arn:aws:events:{region}:{account_id}:replay/{name}".format(
region=self.region, account_id=ACCOUNT_ID, name=self.name region=self.region, account_id=get_account_id(), name=self.name
) )
def describe_short(self): def describe_short(self):
@ -695,7 +695,7 @@ class Connection(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:events:{0}:{1}:connection/{2}/{3}".format( return "arn:aws:events:{0}:{1}:connection/{2}/{3}".format(
self.region, ACCOUNT_ID, self.name, self.uuid self.region, get_account_id(), self.name, self.uuid
) )
def describe_short(self): def describe_short(self):
@ -776,7 +776,7 @@ class Destination(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:events:{0}:{1}:api-destination/{2}/{3}".format( return "arn:aws:events:{0}:{1}:api-destination/{2}/{3}".format(
self.region, ACCOUNT_ID, self.name, self.uuid self.region, get_account_id(), self.name, self.uuid
) )
def describe(self): def describe(self):
@ -1221,7 +1221,7 @@ class EventsBackend(BaseBackend):
"id": event_id, "id": event_id,
"detail-type": event["DetailType"], "detail-type": event["DetailType"],
"source": event["Source"], "source": event["Source"],
"account": ACCOUNT_ID, "account": get_account_id(),
"time": event.get("Time", unix_time(datetime.utcnow())), "time": event.get("Time", unix_time(datetime.utcnow())),
"region": self.region_name, "region": self.region_name,
"resources": event.get("Resources", []), "resources": event.get("Resources", []),

View File

@ -27,7 +27,7 @@ import warnings
import requests import requests
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.firehose.exceptions import ( from moto.firehose.exceptions import (
ConcurrentModificationException, ConcurrentModificationException,
@ -151,7 +151,7 @@ class DeliveryStream(
del self.destinations[0][destination_name]["S3Configuration"] del self.destinations[0][destination_name]["S3Configuration"]
self.delivery_stream_status = "ACTIVE" self.delivery_stream_status = "ACTIVE"
self.delivery_stream_arn = f"arn:aws:firehose:{region}:{ACCOUNT_ID}:deliverystream/{delivery_stream_name}" self.delivery_stream_arn = f"arn:aws:firehose:{region}:{get_account_id()}:deliverystream/{delivery_stream_name}"
self.create_timestamp = datetime.now(timezone.utc).isoformat() self.create_timestamp = datetime.now(timezone.utc).isoformat()
self.version_id = "1" # Used to track updates of destination configs self.version_id = "1" # Used to track updates of destination configs
@ -203,7 +203,7 @@ class FirehoseBackend(BaseBackend):
if delivery_stream_name in self.delivery_streams: if delivery_stream_name in self.delivery_streams:
raise ResourceInUseException( raise ResourceInUseException(
f"Firehose {delivery_stream_name} under accountId {ACCOUNT_ID} " f"Firehose {delivery_stream_name} under accountId {get_account_id()} "
f"already exists" f"already exists"
) )
@ -272,7 +272,7 @@ class FirehoseBackend(BaseBackend):
delivery_stream = self.delivery_streams.get(delivery_stream_name) delivery_stream = self.delivery_streams.get(delivery_stream_name)
if not delivery_stream: if not delivery_stream:
raise ResourceNotFoundException( raise ResourceNotFoundException(
f"Firehose {delivery_stream_name} under account {ACCOUNT_ID} " f"Firehose {delivery_stream_name} under account {get_account_id()} "
f"not found." f"not found."
) )
@ -292,7 +292,7 @@ class FirehoseBackend(BaseBackend):
delivery_stream = self.delivery_streams.get(delivery_stream_name) delivery_stream = self.delivery_streams.get(delivery_stream_name)
if not delivery_stream: if not delivery_stream:
raise ResourceNotFoundException( raise ResourceNotFoundException(
f"Firehose {delivery_stream_name} under account {ACCOUNT_ID} " f"Firehose {delivery_stream_name} under account {get_account_id()} "
f"not found." f"not found."
) )
@ -376,7 +376,7 @@ class FirehoseBackend(BaseBackend):
delivery_stream = self.delivery_streams.get(delivery_stream_name) delivery_stream = self.delivery_streams.get(delivery_stream_name)
if not delivery_stream: if not delivery_stream:
raise ResourceNotFoundException( raise ResourceNotFoundException(
f"Firehose {delivery_stream_name} under account {ACCOUNT_ID} " f"Firehose {delivery_stream_name} under account {get_account_id()} "
f"not found." f"not found."
) )
@ -466,7 +466,7 @@ class FirehoseBackend(BaseBackend):
delivery_stream = self.delivery_streams.get(delivery_stream_name) delivery_stream = self.delivery_streams.get(delivery_stream_name)
if not delivery_stream: if not delivery_stream:
raise ResourceNotFoundException( raise ResourceNotFoundException(
f"Firehose {delivery_stream_name} under account {ACCOUNT_ID} " f"Firehose {delivery_stream_name} under account {get_account_id()} "
f"not found." f"not found."
) )
@ -512,7 +512,7 @@ class FirehoseBackend(BaseBackend):
delivery_stream = self.delivery_streams.get(delivery_stream_name) delivery_stream = self.delivery_streams.get(delivery_stream_name)
if not delivery_stream: if not delivery_stream:
raise ResourceNotFoundException( raise ResourceNotFoundException(
f"Firehose {delivery_stream_name} under account {ACCOUNT_ID} " f"Firehose {delivery_stream_name} under account {get_account_id()} "
f"not found." f"not found."
) )
@ -534,7 +534,7 @@ class FirehoseBackend(BaseBackend):
delivery_stream = self.delivery_streams.get(delivery_stream_name) delivery_stream = self.delivery_streams.get(delivery_stream_name)
if not delivery_stream: if not delivery_stream:
raise ResourceNotFoundException( raise ResourceNotFoundException(
f"Firehose {delivery_stream_name} under account {ACCOUNT_ID} " f"Firehose {delivery_stream_name} under account {get_account_id()} "
f"not found." f"not found."
) )
@ -565,7 +565,7 @@ class FirehoseBackend(BaseBackend):
if not delivery_stream: if not delivery_stream:
raise ResourceNotFoundException( raise ResourceNotFoundException(
f"Firehose {delivery_stream_name} under accountId " f"Firehose {delivery_stream_name} under accountId "
f"{ACCOUNT_ID} not found." f"{get_account_id()} not found."
) )
if destination_name == "Splunk": if destination_name == "Splunk":
@ -653,7 +653,7 @@ class FirehoseBackend(BaseBackend):
"logGroup": log_group_name, "logGroup": log_group_name,
"logStream": log_stream_name, "logStream": log_stream_name,
"messageType": "DATA_MESSAGE", "messageType": "DATA_MESSAGE",
"owner": ACCOUNT_ID, "owner": get_account_id(),
"subscriptionFilters": [filter_name], "subscriptionFilters": [filter_name],
} }

View File

@ -1,7 +1,7 @@
import re import re
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend from moto.core import get_account_id, BaseBackend
from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict
from .exceptions import ( from .exceptions import (
InvalidInputException, InvalidInputException,
@ -34,7 +34,7 @@ class DatasetGroup:
"arn:aws:forecast:" "arn:aws:forecast:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":dataset-group/" + ":dataset-group/"
+ dataset_group_name + dataset_group_name
) )

View File

@ -2,7 +2,7 @@ import hashlib
import datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from .utils import get_job_id from .utils import get_job_id
@ -99,7 +99,7 @@ class Vault(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:glacier:{0}:{1}:vaults/{2}".format( return "arn:aws:glacier:{0}:{1}:vaults/{2}".format(
self.region, ACCOUNT_ID, self.vault_name self.region, get_account_id(), self.vault_name
) )
def to_dict(self): def to_dict(self):

View File

@ -22,7 +22,7 @@ from botocore.auth import SigV4Auth, S3SigV4Auth
from botocore.awsrequest import AWSRequest from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials from botocore.credentials import Credentials
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.exceptions import ( from moto.core.exceptions import (
SignatureDoesNotMatchError, SignatureDoesNotMatchError,
AccessDeniedError, AccessDeniedError,
@ -69,7 +69,7 @@ class IAMUserAccessKey(object):
@property @property
def arn(self): def arn(self):
return "arn:aws:iam::{account_id}:user/{iam_user_name}".format( return "arn:aws:iam::{account_id}:user/{iam_user_name}".format(
account_id=ACCOUNT_ID, iam_user_name=self._owner_user_name account_id=get_account_id(), iam_user_name=self._owner_user_name
) )
def create_credentials(self): def create_credentials(self):
@ -125,7 +125,7 @@ class AssumedRoleAccessKey(object):
def arn(self): def arn(self):
return ( return (
"arn:aws:sts::{account_id}:assumed-role/{role_name}/{session_name}".format( "arn:aws:sts::{account_id}:assumed-role/{role_name}/{session_name}".format(
account_id=ACCOUNT_ID, account_id=get_account_id(),
role_name=self._owner_role_name, role_name=self._owner_role_name,
session_name=self._session_name, session_name=self._session_name,
) )

View File

@ -16,7 +16,7 @@ from cryptography.hazmat.backends import default_backend
from jinja2 import Template from jinja2 import Template
from urllib import parse from urllib import parse
from moto.core.exceptions import RESTError from moto.core.exceptions import RESTError
from moto.core import BaseBackend, BaseModel, ACCOUNT_ID, CloudFormationModel from moto.core import BaseBackend, BaseModel, get_account_id, CloudFormationModel
from moto.core.utils import ( from moto.core.utils import (
iso_8601_datetime_without_milliseconds, iso_8601_datetime_without_milliseconds,
iso_8601_datetime_with_milliseconds, iso_8601_datetime_with_milliseconds,
@ -74,7 +74,9 @@ class MFADevice(object):
class VirtualMfaDevice(object): class VirtualMfaDevice(object):
def __init__(self, device_name): def __init__(self, device_name):
self.serial_number = "arn:aws:iam::{0}:mfa{1}".format(ACCOUNT_ID, device_name) self.serial_number = "arn:aws:iam::{0}:mfa{1}".format(
get_account_id(), device_name
)
random_base32_string = "".join( random_base32_string = "".join(
random.choice(string.ascii_uppercase + "234567") for _ in range(64) random.choice(string.ascii_uppercase + "234567") for _ in range(64)
@ -163,7 +165,7 @@ class SAMLProvider(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:iam::{0}:saml-provider/{1}".format(ACCOUNT_ID, self.name) return "arn:aws:iam::{0}:saml-provider/{1}".format(get_account_id(), self.name)
class OpenIDConnectProvider(BaseModel): class OpenIDConnectProvider(BaseModel):
@ -180,7 +182,7 @@ class OpenIDConnectProvider(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:iam::{0}:oidc-provider/{1}".format(ACCOUNT_ID, self.url) return "arn:aws:iam::{0}:oidc-provider/{1}".format(get_account_id(), self.url)
@property @property
def created_iso_8601(self): def created_iso_8601(self):
@ -285,7 +287,9 @@ class ManagedPolicy(Policy, CloudFormationModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:iam::{0}:policy{1}{2}".format(ACCOUNT_ID, self.path, self.name) return "arn:aws:iam::{0}:policy{1}{2}".format(
get_account_id(), self.path, self.name
)
def to_config_dict(self): def to_config_dict(self):
return { return {
@ -295,7 +299,7 @@ class ManagedPolicy(Policy, CloudFormationModel):
"configurationStateId": str( "configurationStateId": str(
int(time.mktime(self.create_date.timetuple())) int(time.mktime(self.create_date.timetuple()))
), # PY2 and 3 compatible ), # PY2 and 3 compatible
"arn": "arn:aws:iam::{}:policy/{}".format(ACCOUNT_ID, self.name), "arn": "arn:aws:iam::{}:policy/{}".format(get_account_id(), self.name),
"resourceType": "AWS::IAM::Policy", "resourceType": "AWS::IAM::Policy",
"resourceId": self.id, "resourceId": self.id,
"resourceName": self.name, "resourceName": self.name,
@ -306,7 +310,7 @@ class ManagedPolicy(Policy, CloudFormationModel):
"configuration": { "configuration": {
"policyName": self.name, "policyName": self.name,
"policyId": self.id, "policyId": self.id,
"arn": "arn:aws:iam::{}:policy/{}".format(ACCOUNT_ID, self.name), "arn": "arn:aws:iam::{}:policy/{}".format(get_account_id(), self.name),
"path": self.path, "path": self.path,
"defaultVersionId": self.default_version_id, "defaultVersionId": self.default_version_id,
"attachmentCount": self.attachment_count, "attachmentCount": self.attachment_count,
@ -636,8 +640,10 @@ class Role(CloudFormationModel):
@property @property
def arn(self): def arn(self):
if self._linked_service: if self._linked_service:
return f"arn:aws:iam::{ACCOUNT_ID}:role/aws-service-role/{self._linked_service}/{self.name}" return f"arn:aws:iam::{get_account_id()}:role/aws-service-role/{self._linked_service}/{self.name}"
return "arn:aws:iam::{0}:role{1}{2}".format(ACCOUNT_ID, self.path, self.name) return "arn:aws:iam::{0}:role{1}{2}".format(
get_account_id(), self.path, self.name
)
def to_config_dict(self): def to_config_dict(self):
_managed_policies = [] _managed_policies = []
@ -665,7 +671,7 @@ class Role(CloudFormationModel):
"configurationStateId": str( "configurationStateId": str(
int(time.mktime(self.create_date.timetuple())) int(time.mktime(self.create_date.timetuple()))
), # PY2 and 3 compatible ), # PY2 and 3 compatible
"arn": "arn:aws:iam::{}:role/{}".format(ACCOUNT_ID, self.name), "arn": "arn:aws:iam::{}:role/{}".format(get_account_id(), self.name),
"resourceType": "AWS::IAM::Role", "resourceType": "AWS::IAM::Role",
"resourceId": self.name, "resourceId": self.name,
"resourceName": self.name, "resourceName": self.name,
@ -679,7 +685,7 @@ class Role(CloudFormationModel):
"path": self.path, "path": self.path,
"roleName": self.name, "roleName": self.name,
"roleId": self.id, "roleId": self.id,
"arn": "arn:aws:iam::{}:role/{}".format(ACCOUNT_ID, self.name), "arn": "arn:aws:iam::{}:role/{}".format(get_account_id(), self.name),
"assumeRolePolicyDocument": parse.quote( "assumeRolePolicyDocument": parse.quote(
self.assume_role_policy_document self.assume_role_policy_document
) )
@ -820,7 +826,7 @@ class InstanceProfile(CloudFormationModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:iam::{0}:instance-profile{1}{2}".format( return "arn:aws:iam::{0}:instance-profile{1}{2}".format(
ACCOUNT_ID, self.path, self.name get_account_id(), self.path, self.name
) )
@property @property
@ -848,7 +854,9 @@ class InstanceProfile(CloudFormationModel):
"path": role.path, "path": role.path,
"roleName": role.name, "roleName": role.name,
"roleId": role.id, "roleId": role.id,
"arn": "arn:aws:iam::{}:role/{}".format(ACCOUNT_ID, role.name), "arn": "arn:aws:iam::{}:role/{}".format(
get_account_id(), role.name
),
"createDate": str(role.create_date), "createDate": str(role.create_date),
"assumeRolePolicyDocument": parse.quote( "assumeRolePolicyDocument": parse.quote(
role.assume_role_policy_document role.assume_role_policy_document
@ -870,7 +878,9 @@ class InstanceProfile(CloudFormationModel):
"path": self.path, "path": self.path,
"instanceProfileName": self.name, "instanceProfileName": self.name,
"instanceProfileId": self.id, "instanceProfileId": self.id,
"arn": "arn:aws:iam::{}:instance-profile/{}".format(ACCOUNT_ID, self.name), "arn": "arn:aws:iam::{}:instance-profile/{}".format(
get_account_id(), self.name
),
"createDate": str(self.create_date), "createDate": str(self.create_date),
"roles": roles, "roles": roles,
} }
@ -893,7 +903,7 @@ class Certificate(BaseModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:iam::{0}:server-certificate{1}{2}".format( return "arn:aws:iam::{0}:server-certificate{1}{2}".format(
ACCOUNT_ID, self.path, self.cert_name get_account_id(), self.path, self.cert_name
) )
@ -1042,11 +1052,11 @@ class Group(BaseModel):
@property @property
def arn(self): def arn(self):
if self.path == "/": if self.path == "/":
return "arn:aws:iam::{0}:group/{1}".format(ACCOUNT_ID, self.name) return "arn:aws:iam::{0}:group/{1}".format(get_account_id(), self.name)
else: else:
return "arn:aws:iam::{0}:group/{1}/{2}".format( return "arn:aws:iam::{0}:group/{1}/{2}".format(
ACCOUNT_ID, self.path, self.name get_account_id(), self.path, self.name
) )
def get_policy(self, policy_name): def get_policy(self, policy_name):
@ -1092,7 +1102,9 @@ class User(CloudFormationModel):
@property @property
def arn(self): def arn(self):
return "arn:aws:iam::{0}:user{1}{2}".format(ACCOUNT_ID, self.path, self.name) return "arn:aws:iam::{0}:user{1}{2}".format(
get_account_id(), self.path, self.name
)
@property @property
def created_iso_8601(self): def created_iso_8601(self):
@ -2781,7 +2793,7 @@ class IAMBackend(BaseBackend):
if not self.account_password_policy: if not self.account_password_policy:
raise NoSuchEntity( raise NoSuchEntity(
"The Password Policy with domain name {} cannot be found.".format( "The Password Policy with domain name {} cannot be found.".format(
ACCOUNT_ID get_account_id()
) )
) )

View File

@ -14,7 +14,7 @@ from datetime import datetime, timedelta
from .utils import PAGINATION_MODEL from .utils import PAGINATION_MODEL
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.utilities.utils import random_string from moto.utilities.utils import random_string
from moto.utilities.paginator import paginate from moto.utilities.paginator import paginate
@ -37,7 +37,7 @@ class FakeThing(BaseModel):
self.thing_name = thing_name self.thing_name = thing_name
self.thing_type = thing_type self.thing_type = thing_type
self.attributes = attributes self.attributes = attributes
self.arn = f"arn:aws:iot:{region_name}:{ACCOUNT_ID}:thing/{thing_name}" self.arn = f"arn:aws:iot:{region_name}:{get_account_id()}:thing/{thing_name}"
self.version = 1 self.version = 1
# TODO: we need to handle "version"? # TODO: we need to handle "version"?
@ -153,11 +153,13 @@ class FakeCertificate(BaseModel):
m = hashlib.sha256() m = hashlib.sha256()
m.update(certificate_pem.encode("utf-8")) m.update(certificate_pem.encode("utf-8"))
self.certificate_id = m.hexdigest() self.certificate_id = m.hexdigest()
self.arn = f"arn:aws:iot:{region_name}:{ACCOUNT_ID}:cert/{self.certificate_id}" self.arn = (
f"arn:aws:iot:{region_name}:{get_account_id()}:cert/{self.certificate_id}"
)
self.certificate_pem = certificate_pem self.certificate_pem = certificate_pem
self.status = status self.status = status
self.owner = ACCOUNT_ID self.owner = get_account_id()
self.transfer_data = {} self.transfer_data = {}
self.creation_date = time.time() self.creation_date = time.time()
self.last_modified_date = self.creation_date self.last_modified_date = self.creation_date
@ -211,7 +213,7 @@ class FakePolicy(BaseModel):
def __init__(self, name, document, region_name, default_version_id="1"): def __init__(self, name, document, region_name, default_version_id="1"):
self.name = name self.name = name
self.document = document self.document = document
self.arn = f"arn:aws:iot:{region_name}:{ACCOUNT_ID}:policy/{name}" self.arn = f"arn:aws:iot:{region_name}:{get_account_id()}:policy/{name}"
self.default_version_id = default_version_id self.default_version_id = default_version_id
self.versions = [FakePolicyVersion(self.name, document, True, region_name)] self.versions = [FakePolicyVersion(self.name, document, True, region_name)]
@ -238,7 +240,7 @@ class FakePolicy(BaseModel):
class FakePolicyVersion(object): class FakePolicyVersion(object):
def __init__(self, policy_name, document, is_default, region_name): def __init__(self, policy_name, document, is_default, region_name):
self.name = policy_name self.name = policy_name
self.arn = f"arn:aws:iot:{region_name}:{ACCOUNT_ID}:policy/{policy_name}" self.arn = f"arn:aws:iot:{region_name}:{get_account_id()}:policy/{policy_name}"
self.document = document or {} self.document = document or {}
self.is_default = is_default self.is_default = is_default
self.version_id = "1" self.version_id = "1"

View File

@ -1,6 +1,6 @@
import json import json
from werkzeug.exceptions import BadRequest from werkzeug.exceptions import BadRequest
from moto.core import ACCOUNT_ID from moto.core import get_account_id
class ResourceNotFoundError(BadRequest): class ResourceNotFoundError(BadRequest):
@ -22,20 +22,22 @@ class ResourceInUseError(BadRequest):
class StreamNotFoundError(ResourceNotFoundError): class StreamNotFoundError(ResourceNotFoundError):
def __init__(self, stream_name): def __init__(self, stream_name):
super().__init__( super().__init__(
"Stream {0} under account {1} not found.".format(stream_name, ACCOUNT_ID) "Stream {0} under account {1} not found.".format(
stream_name, get_account_id()
)
) )
class ShardNotFoundError(ResourceNotFoundError): class ShardNotFoundError(ResourceNotFoundError):
def __init__(self, shard_id, stream): def __init__(self, shard_id, stream):
super().__init__( super().__init__(
f"Could not find shard {shard_id} in stream {stream} under account {ACCOUNT_ID}." f"Could not find shard {shard_id} in stream {stream} under account {get_account_id()}."
) )
class ConsumerNotFound(ResourceNotFoundError): class ConsumerNotFound(ResourceNotFoundError):
def __init__(self, consumer): def __init__(self, consumer):
super().__init__(f"Consumer {consumer}, account {ACCOUNT_ID} not found.") super().__init__(f"Consumer {consumer}, account {get_account_id()} not found.")
class InvalidArgumentError(BadRequest): class InvalidArgumentError(BadRequest):

View File

@ -8,7 +8,7 @@ from hashlib import md5
from moto.core import BaseBackend, BaseModel, CloudFormationModel from moto.core import BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import unix_time, BackendDict from moto.core.utils import unix_time, BackendDict
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.utilities.paginator import paginate from moto.utilities.paginator import paginate
from .exceptions import ( from .exceptions import (
ConsumerNotFound, ConsumerNotFound,
@ -36,7 +36,7 @@ class Consumer(BaseModel):
self.created = unix_time() self.created = unix_time()
self.stream_arn = stream_arn self.stream_arn = stream_arn
stream_name = stream_arn.split("/")[-1] stream_name = stream_arn.split("/")[-1]
self.consumer_arn = f"arn:aws:kinesis:{region_name}:{ACCOUNT_ID}:stream/{stream_name}/consumer/{consumer_name}" self.consumer_arn = f"arn:aws:kinesis:{region_name}:{get_account_id()}:stream/{stream_name}/consumer/{consumer_name}"
def to_json(self, include_stream_arn=False): def to_json(self, include_stream_arn=False):
resp = { resp = {
@ -170,7 +170,7 @@ class Stream(CloudFormationModel):
"%Y-%m-%dT%H:%M:%S.%f000" "%Y-%m-%dT%H:%M:%S.%f000"
) )
self.region = region_name self.region = region_name
self.account_number = ACCOUNT_ID self.account_number = get_account_id()
self.shards = {} self.shards = {}
self.tags = {} self.tags = {}
self.status = "ACTIVE" self.status = "ACTIVE"
@ -211,12 +211,12 @@ class Stream(CloudFormationModel):
pass pass
else: else:
raise InvalidArgumentError( raise InvalidArgumentError(
message=f"NewStartingHashKey {new_starting_hash_key} used in SplitShard() on shard {shard_to_split} in stream {self.stream_name} under account {ACCOUNT_ID} is not both greater than one plus the shard's StartingHashKey {shard.starting_hash} and less than the shard's EndingHashKey {(shard.ending_hash - 1)}." message=f"NewStartingHashKey {new_starting_hash_key} used in SplitShard() on shard {shard_to_split} in stream {self.stream_name} under account {get_account_id()} is not both greater than one plus the shard's StartingHashKey {shard.starting_hash} and less than the shard's EndingHashKey {(shard.ending_hash - 1)}."
) )
if not shard.is_open: if not shard.is_open:
raise InvalidArgumentError( raise InvalidArgumentError(
message=f"Shard {shard.shard_id} in stream {self.stream_name} under account {ACCOUNT_ID} has already been merged or split, and thus is not eligible for merging or splitting." message=f"Shard {shard.shard_id} in stream {self.stream_name} under account {get_account_id()} has already been merged or split, and thus is not eligible for merging or splitting."
) )
last_id = sorted(self.shards.values(), key=attrgetter("_shard_id"))[ last_id = sorted(self.shards.values(), key=attrgetter("_shard_id"))[
@ -556,7 +556,7 @@ class KinesisBackend(BaseBackend):
shard = stream.get_shard(shard_id) shard = stream.get_shard(shard_id)
except ShardNotFoundError: except ShardNotFoundError:
raise ResourceNotFoundError( raise ResourceNotFoundError(
message=f"Shard {shard_id} in stream {stream_name} under account {ACCOUNT_ID} does not exist" message=f"Shard {shard_id} in stream {stream_name} under account {get_account_id()} does not exist"
) )
shard_iterator = compose_new_shard_iterator( shard_iterator = compose_new_shard_iterator(

View File

@ -4,7 +4,7 @@ from .exceptions import ResourceNotFoundException, ResourceInUseException
import random import random
import string import string
from moto.core.utils import get_random_hex, BackendDict from moto.core.utils import get_random_hex, BackendDict
from moto.core import ACCOUNT_ID from moto.core import get_account_id
class Stream(BaseModel): class Stream(BaseModel):
@ -29,7 +29,7 @@ class Stream(BaseModel):
self.version = self._get_random_string() self.version = self._get_random_string()
self.creation_time = datetime.utcnow() self.creation_time = datetime.utcnow()
stream_arn = "arn:aws:kinesisvideo:{}:{}:stream/{}/1598784211076".format( stream_arn = "arn:aws:kinesisvideo:{}:{}:stream/{}/1598784211076".format(
self.region_name, ACCOUNT_ID, self.stream_name self.region_name, get_account_id(), self.stream_name
) )
self.data_endpoint_number = get_random_hex() self.data_endpoint_number = get_random_hex()
self.arn = stream_arn self.arn = stream_arn

View File

@ -3,7 +3,7 @@ import os
from collections import defaultdict from collections import defaultdict
from datetime import datetime, timedelta from datetime import datetime, timedelta
from moto.core import ACCOUNT_ID, BaseBackend, CloudFormationModel from moto.core import get_account_id, BaseBackend, CloudFormationModel
from moto.core.utils import unix_time, BackendDict from moto.core.utils import unix_time, BackendDict
from moto.utilities.tagging_service import TaggingService from moto.utilities.tagging_service import TaggingService
from moto.core.exceptions import JsonRESTError from moto.core.exceptions import JsonRESTError
@ -29,7 +29,7 @@ class Key(CloudFormationModel):
self.description = description or "" self.description = description or ""
self.enabled = True self.enabled = True
self.region = region self.region = region
self.account_id = ACCOUNT_ID self.account_id = get_account_id()
self.key_rotation_status = False self.key_rotation_status = False
self.deletion_date = None self.deletion_date = None
self.key_material = generate_master_key() self.key_material = generate_master_key()
@ -46,7 +46,7 @@ class Key(CloudFormationModel):
{ {
"Sid": "Enable IAM User Permissions", "Sid": "Enable IAM User Permissions",
"Effect": "Allow", "Effect": "Allow",
"Principal": {"AWS": f"arn:aws:iam::{ACCOUNT_ID}:root"}, "Principal": {"AWS": f"arn:aws:iam::{get_account_id()}:root"},
"Action": "kms:*", "Action": "kms:*",
"Resource": "*", "Resource": "*",
} }

View File

@ -3,7 +3,7 @@ import json
import os import os
import re import re
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.responses import BaseResponse from moto.core.responses import BaseResponse
from moto.kms.utils import RESERVED_ALIASES from moto.kms.utils import RESERVED_ALIASES
from .models import kms_backends from .models import kms_backends
@ -40,7 +40,7 @@ class KmsResponse(BaseResponse):
id_type = "key/" id_type = "key/"
return "arn:aws:kms:{region}:{account}:{id_type}{key_id}".format( return "arn:aws:kms:{region}:{account}:{id_type}{key_id}".format(
region=self.region, account=ACCOUNT_ID, id_type=id_type, key_id=key_id region=self.region, account=get_account_id(), id_type=id_type, key_id=key_id
) )
def _validate_cmk_id(self, key_id): def _validate_cmk_id(self, key_id):
@ -221,7 +221,9 @@ class KmsResponse(BaseResponse):
raise AlreadyExistsException( raise AlreadyExistsException(
"An alias with the name arn:aws:kms:{region}:{account_id}:{alias_name} " "An alias with the name arn:aws:kms:{region}:{account_id}:{alias_name} "
"already exists".format( "already exists".format(
region=self.region, account_id=ACCOUNT_ID, alias_name=alias_name region=self.region,
account_id=get_account_id(),
alias_name=alias_name,
) )
) )
@ -256,7 +258,9 @@ class KmsResponse(BaseResponse):
response_aliases.append( response_aliases.append(
{ {
"AliasArn": "arn:aws:kms:{region}:{account_id}:{alias_name}".format( "AliasArn": "arn:aws:kms:{region}:{account_id}:{alias_name}".format(
region=region, account_id=ACCOUNT_ID, alias_name=alias_name region=region,
account_id=get_account_id(),
alias_name=alias_name,
), ),
"AliasName": alias_name, "AliasName": alias_name,
"TargetKeyId": target_key_id, "TargetKeyId": target_key_id,
@ -271,7 +275,7 @@ class KmsResponse(BaseResponse):
{ {
"AliasArn": "arn:aws:kms:{region}:{account_id}:{reserved_alias}".format( "AliasArn": "arn:aws:kms:{region}:{account_id}:{reserved_alias}".format(
region=region, region=region,
account_id=ACCOUNT_ID, account_id=get_account_id(),
reserved_alias=reserved_alias, reserved_alias=reserved_alias,
), ),
"AliasName": reserved_alias, "AliasName": reserved_alias,

View File

@ -2,7 +2,7 @@ import uuid
from datetime import datetime, timedelta from datetime import datetime, timedelta
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.models import CloudFormationModel from moto.core.models import CloudFormationModel
from moto.core.utils import unix_time_millis, BackendDict from moto.core.utils import unix_time_millis, BackendDict
from moto.utilities.paginator import paginate from moto.utilities.paginator import paginate
@ -60,7 +60,7 @@ class LogStream(BaseModel):
def __init__(self, region, log_group, name): def __init__(self, region, log_group, name):
self.region = region self.region = region
self.arn = f"arn:aws:logs:{region}:{ACCOUNT_ID}:log-group:{log_group}:log-stream:{name}" self.arn = f"arn:aws:logs:{region}:{get_account_id()}:log-group:{log_group}:log-stream:{name}"
self.creation_time = int(unix_time_millis()) self.creation_time = int(unix_time_millis())
self.first_event_timestamp = None self.first_event_timestamp = None
self.last_event_timestamp = None self.last_event_timestamp = None
@ -261,7 +261,7 @@ class LogGroup(CloudFormationModel):
def __init__(self, region, name, tags, **kwargs): def __init__(self, region, name, tags, **kwargs):
self.name = name self.name = name
self.region = region self.region = region
self.arn = f"arn:aws:logs:{region}:{ACCOUNT_ID}:log-group:{name}" self.arn = f"arn:aws:logs:{region}:{get_account_id()}:log-group:{name}"
self.creation_time = int(unix_time_millis()) self.creation_time = int(unix_time_millis())
self.tags = tags self.tags = tags
self.streams = dict() # {name: LogStream} self.streams = dict() # {name: LogStream}

View File

@ -1,7 +1,7 @@
from collections import OrderedDict from collections import OrderedDict
from uuid import uuid4 from uuid import uuid4
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.mediaconnect.exceptions import NotFoundException from moto.mediaconnect.exceptions import NotFoundException
@ -81,7 +81,7 @@ class MediaConnectBackend(BaseBackend):
def _add_source_details(self, source, flow_id, ingest_ip="127.0.0.1"): def _add_source_details(self, source, flow_id, ingest_ip="127.0.0.1"):
if source: if source:
source["sourceArn"] = ( source["sourceArn"] = (
f"arn:aws:mediaconnect:{self.region_name}:{ACCOUNT_ID}:source" f"arn:aws:mediaconnect:{self.region_name}:{get_account_id()}:source"
f":{flow_id}:{source['name']}" f":{flow_id}:{source['name']}"
) )
if not source.get("entitlementArn"): if not source.get("entitlementArn"):
@ -92,7 +92,7 @@ class MediaConnectBackend(BaseBackend):
flow.description = "A Moto test flow" flow.description = "A Moto test flow"
flow.egress_ip = "127.0.0.1" flow.egress_ip = "127.0.0.1"
flow.flow_arn = f"arn:aws:mediaconnect:{self.region_name}:{ACCOUNT_ID}:flow:{flow_id}:{flow.name}" flow.flow_arn = f"arn:aws:mediaconnect:{self.region_name}:{get_account_id()}:flow:{flow_id}:{flow.name}"
for index, _source in enumerate(flow.sources): for index, _source in enumerate(flow.sources):
self._add_source_details(_source, flow_id, f"127.0.0.{index}") self._add_source_details(_source, flow_id, f"127.0.0.{index}")

View File

@ -1,7 +1,7 @@
import base64 import base64
import xmltodict import xmltodict
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict, get_random_hex, unix_time from moto.core.utils import BackendDict, get_random_hex, unix_time
from moto.utilities.tagging_service import TaggingService from moto.utilities.tagging_service import TaggingService
@ -59,7 +59,7 @@ class ConfigurationRevision(BaseModel):
class Configuration(BaseModel): class Configuration(BaseModel):
def __init__(self, region, name, engine_type, engine_version): def __init__(self, region, name, engine_type, engine_version):
self.id = f"c-{get_random_hex(6)}" self.id = f"c-{get_random_hex(6)}"
self.arn = f"arn:aws:mq:{region}:{ACCOUNT_ID}:configuration:{self.id}" self.arn = f"arn:aws:mq:{region}:{get_account_id()}:configuration:{self.id}"
self.created = unix_time() self.created = unix_time()
self.name = name self.name = name
@ -160,7 +160,7 @@ class Broker(BaseModel):
): ):
self.name = name self.name = name
self.id = get_random_hex(6) self.id = get_random_hex(6)
self.arn = f"arn:aws:mq:{region}:{ACCOUNT_ID}:broker:{self.id}" self.arn = f"arn:aws:mq:{region}:{get_account_id()}:broker:{self.id}"
self.state = "RUNNING" self.state = "RUNNING"
self.created = unix_time() self.created = unix_time()

View File

@ -1,6 +1,6 @@
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.ec2 import ec2_backends from moto.ec2 import ec2_backends
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
import uuid import uuid
import datetime import datetime
@ -371,7 +371,7 @@ class Stack(BaseModel):
self.id = "{0}".format(uuid.uuid4()) self.id = "{0}".format(uuid.uuid4())
self.layers = [] self.layers = []
self.apps = [] self.apps = []
self.account_number = ACCOUNT_ID self.account_number = get_account_id()
self.created_at = datetime.datetime.utcnow() self.created_at = datetime.datetime.utcnow()
def __eq__(self, other): def __eq__(self, other):

View File

@ -2,7 +2,7 @@ import datetime
import re import re
import json import json
from moto.core import BaseBackend, BaseModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, get_account_id
from moto.core.exceptions import RESTError from moto.core.exceptions import RESTError
from moto.core.utils import unix_time from moto.core.utils import unix_time
from moto.organizations import utils from moto.organizations import utils
@ -774,7 +774,7 @@ class OrganizationsBackend(BaseBackend):
def register_delegated_administrator(self, **kwargs): def register_delegated_administrator(self, **kwargs):
account_id = kwargs["AccountId"] account_id = kwargs["AccountId"]
if account_id == ACCOUNT_ID: if account_id == get_account_id():
raise ConstraintViolationException( raise ConstraintViolationException(
"You cannot register master account/yourself as delegated administrator for your organization." "You cannot register master account/yourself as delegated administrator for your organization."
) )
@ -833,7 +833,7 @@ class OrganizationsBackend(BaseBackend):
account_id = kwargs["AccountId"] account_id = kwargs["AccountId"]
service = kwargs["ServicePrincipal"] service = kwargs["ServicePrincipal"]
if account_id == ACCOUNT_ID: if account_id == get_account_id():
raise ConstraintViolationException( raise ConstraintViolationException(
"You cannot register master account/yourself as delegated administrator for your organization." "You cannot register master account/yourself as delegated administrator for your organization."
) )

View File

@ -1,10 +1,10 @@
import random import random
import re import re
import string import string
from moto.core import ACCOUNT_ID from moto.core import get_account_id
MASTER_ACCOUNT_ID = ACCOUNT_ID MASTER_ACCOUNT_ID = get_account_id()
MASTER_ACCOUNT_EMAIL = "master@example.com" MASTER_ACCOUNT_EMAIL = "master@example.com"
DEFAULT_POLICY_ID = "p-FullAWSAccess" DEFAULT_POLICY_ID = "p-FullAWSAccess"
ORGANIZATION_ARN_FORMAT = "arn:aws:organizations::{0}:organization/{1}" ORGANIZATION_ARN_FORMAT = "arn:aws:organizations::{0}:organization/{1}"

View File

@ -1,5 +1,5 @@
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict, unix_time from moto.core.utils import BackendDict, unix_time
from moto.utilities.tagging_service import TaggingService from moto.utilities.tagging_service import TaggingService
from uuid import uuid4 from uuid import uuid4
@ -10,9 +10,7 @@ from .exceptions import ApplicationNotFound, EventStreamNotFound
class App(BaseModel): class App(BaseModel):
def __init__(self, name): def __init__(self, name):
self.application_id = str(uuid4()).replace("-", "") self.application_id = str(uuid4()).replace("-", "")
self.arn = ( self.arn = f"arn:aws:mobiletargeting:us-east-1:{get_account_id()}:apps/{self.application_id}"
f"arn:aws:mobiletargeting:us-east-1:{ACCOUNT_ID}:apps/{self.application_id}"
)
self.name = name self.name = name
self.created = unix_time() self.created = unix_time()
self.settings = AppSettings() self.settings = AppSettings()

View File

@ -7,7 +7,7 @@ from moto.core.utils import BackendDict
from .resources import VOICE_DATA from .resources import VOICE_DATA
from .utils import make_arn_for_lexicon from .utils import make_arn_for_lexicon
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.core import get_account_id
class Lexicon(BaseModel): class Lexicon(BaseModel):
@ -19,7 +19,7 @@ class Lexicon(BaseModel):
self.last_modified = None self.last_modified = None
self.language_code = None self.language_code = None
self.lexemes_count = 0 self.lexemes_count = 0
self.arn = make_arn_for_lexicon(DEFAULT_ACCOUNT_ID, name, region_name) self.arn = make_arn_for_lexicon(get_account_id(), name, region_name)
self.update() self.update()

View File

@ -1,6 +1,6 @@
"""QuickSightBackend class with methods for supported APIs.""" """QuickSightBackend class with methods for supported APIs."""
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from .exceptions import ResourceNotFoundException from .exceptions import ResourceNotFoundException
@ -11,7 +11,7 @@ def _create_id(aws_account_id, namespace, _id):
class QuicksightDataSet(BaseModel): class QuicksightDataSet(BaseModel):
def __init__(self, region, _id, name): def __init__(self, region, _id, name):
self.arn = f"arn:aws:quicksight:{region}:{ACCOUNT_ID}:data-set/{_id}" self.arn = f"arn:aws:quicksight:{region}:{get_account_id()}:data-set/{_id}"
self._id = _id self._id = _id
self.name = name self.name = name
self.region = region self.region = region
@ -20,13 +20,13 @@ class QuicksightDataSet(BaseModel):
return { return {
"Arn": self.arn, "Arn": self.arn,
"DataSetId": self._id, "DataSetId": self._id,
"IngestionArn": f"arn:aws:quicksight:{self.region}:{ACCOUNT_ID}:ingestion/tbd", "IngestionArn": f"arn:aws:quicksight:{self.region}:{get_account_id()}:ingestion/tbd",
} }
class QuicksightIngestion(BaseModel): class QuicksightIngestion(BaseModel):
def __init__(self, region, data_set_id, ingestion_id): def __init__(self, region, data_set_id, ingestion_id):
self.arn = f"arn:aws:quicksight:{region}:{ACCOUNT_ID}:data-set/{data_set_id}/ingestions/{ingestion_id}" self.arn = f"arn:aws:quicksight:{region}:{get_account_id()}:data-set/{data_set_id}/ingestions/{ingestion_id}"
self.ingestion_id = ingestion_id self.ingestion_id = ingestion_id
def to_json(self): def to_json(self):
@ -41,9 +41,7 @@ class QuicksightMembership(BaseModel):
def __init__(self, region, group, user): def __init__(self, region, group, user):
self.group = group self.group = group
self.user = user self.user = user
self.arn = ( self.arn = f"arn:aws:quicksight:{region}:{get_account_id()}:group/default/{group}/{user}"
f"arn:aws:quicksight:{region}:{ACCOUNT_ID}:group/default/{group}/{user}"
)
def to_json(self): def to_json(self):
return {"Arn": self.arn, "MemberName": self.user} return {"Arn": self.arn, "MemberName": self.user}
@ -52,7 +50,7 @@ class QuicksightMembership(BaseModel):
class QuicksightGroup(BaseModel): class QuicksightGroup(BaseModel):
def __init__(self, region, group_name, description, aws_account_id, namespace): def __init__(self, region, group_name, description, aws_account_id, namespace):
self.arn = ( self.arn = (
f"arn:aws:quicksight:{region}:{ACCOUNT_ID}:group/default/{group_name}" f"arn:aws:quicksight:{region}:{get_account_id()}:group/default/{group_name}"
) )
self.group_name = group_name self.group_name = group_name
self.description = description self.description = description
@ -88,7 +86,9 @@ class QuicksightGroup(BaseModel):
class QuicksightUser(BaseModel): class QuicksightUser(BaseModel):
def __init__(self, region, email, identity_type, username, user_role): def __init__(self, region, email, identity_type, username, user_role):
self.arn = f"arn:aws:quicksight:{region}:{ACCOUNT_ID}:user/default/{username}" self.arn = (
f"arn:aws:quicksight:{region}:{get_account_id()}:user/default/{username}"
)
self.email = email self.email = email
self.identity_type = identity_type self.identity_type = identity_type
self.username = username self.username = username

View File

@ -4,7 +4,7 @@ from datetime import datetime
import random import random
from uuid import uuid4 from uuid import uuid4
from moto.core import BaseBackend, BaseModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, get_account_id
from moto.core.utils import unix_time, BackendDict from moto.core.utils import unix_time, BackendDict
from moto.organizations import organizations_backends from moto.organizations import organizations_backends
from moto.ram.exceptions import ( from moto.ram.exceptions import (
@ -43,13 +43,13 @@ class ResourceShare(BaseModel):
self.allow_external_principals = kwargs.get("allowExternalPrincipals", True) self.allow_external_principals = kwargs.get("allowExternalPrincipals", True)
self.arn = "arn:aws:ram:{0}:{1}:resource-share/{2}".format( self.arn = "arn:aws:ram:{0}:{1}:resource-share/{2}".format(
self.region, ACCOUNT_ID, uuid4() self.region, get_account_id(), uuid4()
) )
self.creation_time = datetime.utcnow() self.creation_time = datetime.utcnow()
self.feature_set = "STANDARD" self.feature_set = "STANDARD"
self.last_updated_time = datetime.utcnow() self.last_updated_time = datetime.utcnow()
self.name = kwargs["name"] self.name = kwargs["name"]
self.owning_account_id = ACCOUNT_ID self.owning_account_id = get_account_id()
self.principals = [] self.principals = []
self.resource_arns = [] self.resource_arns = []
self.status = "ACTIVE" self.status = "ACTIVE"

View File

@ -8,7 +8,7 @@ from collections import defaultdict
from jinja2 import Template from jinja2 import Template
from re import compile as re_compile from re import compile as re_compile
from collections import OrderedDict from collections import OrderedDict
from moto.core import BaseBackend, BaseModel, CloudFormationModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, CloudFormationModel, get_account_id
from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict
from moto.ec2.models import ec2_backends from moto.ec2.models import ec2_backends
@ -114,7 +114,7 @@ class Cluster:
@property @property
def db_cluster_arn(self): def db_cluster_arn(self):
return "arn:aws:rds:{0}:{1}:cluster:{2}".format( return "arn:aws:rds:{0}:{1}:cluster:{2}".format(
self.region, ACCOUNT_ID, self.db_cluster_identifier self.region, get_account_id(), self.db_cluster_identifier
) )
def to_xml(self): def to_xml(self):
@ -258,7 +258,7 @@ class ClusterSnapshot(BaseModel):
@property @property
def snapshot_arn(self): def snapshot_arn(self):
return "arn:aws:rds:{0}:{1}:cluster-snapshot:{2}".format( return "arn:aws:rds:{0}:{1}:cluster-snapshot:{2}".format(
self.cluster.region, ACCOUNT_ID, self.snapshot_id self.cluster.region, get_account_id(), self.snapshot_id
) )
def to_xml(self): def to_xml(self):
@ -430,7 +430,7 @@ class Database(CloudFormationModel):
@property @property
def db_instance_arn(self): def db_instance_arn(self):
return "arn:aws:rds:{0}:{1}:db:{2}".format( return "arn:aws:rds:{0}:{1}:db:{2}".format(
self.region, ACCOUNT_ID, self.db_instance_identifier self.region, get_account_id(), self.db_instance_identifier
) )
@property @property
@ -849,7 +849,7 @@ class DatabaseSnapshot(BaseModel):
@property @property
def snapshot_arn(self): def snapshot_arn(self):
return "arn:aws:rds:{0}:{1}:snapshot:{2}".format( return "arn:aws:rds:{0}:{1}:snapshot:{2}".format(
self.database.region, ACCOUNT_ID, self.snapshot_id self.database.region, get_account_id(), self.snapshot_id
) )
def to_xml(self): def to_xml(self):
@ -958,14 +958,14 @@ class EventSubscription(BaseModel):
self.tags = kwargs.get("tags", True) self.tags = kwargs.get("tags", True)
self.region = "" self.region = ""
self.customer_aws_id = copy.copy(ACCOUNT_ID) self.customer_aws_id = copy.copy(get_account_id())
self.status = "active" self.status = "active"
self.created_at = iso_8601_datetime_with_milliseconds(datetime.datetime.now()) self.created_at = iso_8601_datetime_with_milliseconds(datetime.datetime.now())
@property @property
def es_arn(self): def es_arn(self):
return "arn:aws:rds:{0}:{1}:es:{2}".format( return "arn:aws:rds:{0}:{1}:es:{2}".format(
self.region, ACCOUNT_ID, self.subscription_name self.region, get_account_id(), self.subscription_name
) )
def to_xml(self): def to_xml(self):
@ -1021,7 +1021,7 @@ class SecurityGroup(CloudFormationModel):
self.ip_ranges = [] self.ip_ranges = []
self.ec2_security_groups = [] self.ec2_security_groups = []
self.tags = tags self.tags = tags
self.owner_id = ACCOUNT_ID self.owner_id = get_account_id()
self.vpc_id = None self.vpc_id = None
def to_xml(self): def to_xml(self):
@ -2123,7 +2123,7 @@ class OptionGroup(object):
def make_rds_arn(region, name): def make_rds_arn(region, name):
return "arn:aws:rds:{0}:{1}:pg:{2}".format(region, ACCOUNT_ID, name) return "arn:aws:rds:{0}:{1}:pg:{2}".format(region, get_account_id(), name)
class DBParameterGroup(CloudFormationModel): class DBParameterGroup(CloudFormationModel):

View File

@ -29,7 +29,7 @@ from .exceptions import (
) )
from moto.core import ACCOUNT_ID from moto.core import get_account_id
class TaggableResourceMixin(object): class TaggableResourceMixin(object):
@ -48,7 +48,7 @@ class TaggableResourceMixin(object):
def arn(self): def arn(self):
return "arn:aws:redshift:{region}:{account_id}:{resource_type}:{resource_id}".format( return "arn:aws:redshift:{region}:{account_id}:{resource_type}:{resource_id}".format(
region=self.region, region=self.region,
account_id=ACCOUNT_ID, account_id=get_account_id(),
resource_type=self.resource_type, resource_type=self.resource_type,
resource_id=self.resource_id, resource_id=self.resource_id,
) )

View File

@ -3,7 +3,7 @@ from builtins import str
import json import json
import re import re
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from .exceptions import BadRequestException from .exceptions import BadRequestException
@ -25,7 +25,7 @@ class FakeResourceGroup(BaseModel):
self._tags = tags self._tags = tags
self._raise_errors() self._raise_errors()
self.arn = "arn:aws:resource-groups:us-west-1:{AccountId}:{name}".format( self.arn = "arn:aws:resource-groups:us-west-1:{AccountId}:{name}".format(
name=name, AccountId=ACCOUNT_ID name=name, AccountId=get_account_id()
) )
self.configuration = configuration self.configuration = configuration

View File

@ -1,6 +1,6 @@
import uuid import uuid
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core import BaseBackend from moto.core import BaseBackend
from moto.core.exceptions import RESTError from moto.core.exceptions import RESTError
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
@ -421,7 +421,7 @@ class ResourceGroupsTaggingAPIBackend(BaseBackend):
continue continue
yield { yield {
"ResourceARN": "arn:aws:ec2:{0}:{1}:vpc/{2}".format( "ResourceARN": "arn:aws:ec2:{0}:{1}:vpc/{2}".format(
self.region_name, ACCOUNT_ID, vpc.id self.region_name, get_account_id(), vpc.id
), ),
"Tags": tags, "Tags": tags,
} }

View File

@ -16,7 +16,7 @@ from moto.route53.exceptions import (
NoSuchQueryLoggingConfig, NoSuchQueryLoggingConfig,
QueryLoggingConfigAlreadyExists, QueryLoggingConfigAlreadyExists,
) )
from moto.core import BaseBackend, BaseModel, CloudFormationModel, ACCOUNT_ID from moto.core import BaseBackend, BaseModel, CloudFormationModel, get_account_id
from moto.utilities.paginator import paginate from moto.utilities.paginator import paginate
from .utils import PAGINATION_MODEL from .utils import PAGINATION_MODEL
@ -532,7 +532,7 @@ class Route53Backend(BaseBackend):
{ {
"HostedZoneId": this_id, "HostedZoneId": this_id,
"Name": zone.name, "Name": zone.name,
"Owner": {"OwningAccount": ACCOUNT_ID}, "Owner": {"OwningAccount": get_account_id()},
} }
) )

View File

@ -4,7 +4,7 @@ from datetime import datetime, timezone
from ipaddress import ip_address, ip_network, IPv4Address from ipaddress import ip_address, ip_network, IPv4Address
import re import re
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.core.utils import get_random_hex, BackendDict from moto.core.utils import get_random_hex, BackendDict
from moto.ec2 import ec2_backends from moto.ec2 import ec2_backends
@ -123,7 +123,7 @@ class ResolverRule(BaseModel): # pylint: disable=too-many-instance-attributes
@property @property
def arn(self): def arn(self):
"""Return ARN for this resolver rule.""" """Return ARN for this resolver rule."""
return f"arn:aws:route53resolver:{self.region}:{ACCOUNT_ID}:resolver-rule/{self.id}" return f"arn:aws:route53resolver:{self.region}:{get_account_id()}:resolver-rule/{self.id}"
def description(self): def description(self):
"""Return a dictionary of relevant info for this resolver rule.""" """Return a dictionary of relevant info for this resolver rule."""
@ -138,7 +138,7 @@ class ResolverRule(BaseModel): # pylint: disable=too-many-instance-attributes
"Name": self.name, "Name": self.name,
"TargetIps": self.target_ips, "TargetIps": self.target_ips,
"ResolverEndpointId": self.resolver_endpoint_id, "ResolverEndpointId": self.resolver_endpoint_id,
"OwnerId": ACCOUNT_ID, "OwnerId": get_account_id(),
"ShareStatus": self.share_status, "ShareStatus": self.share_status,
"CreationTime": self.creation_time, "CreationTime": self.creation_time,
"ModificationTime": self.modification_time, "ModificationTime": self.modification_time,
@ -204,7 +204,7 @@ class ResolverEndpoint(BaseModel): # pylint: disable=too-many-instance-attribut
@property @property
def arn(self): def arn(self):
"""Return ARN for this resolver endpoint.""" """Return ARN for this resolver endpoint."""
return f"arn:aws:route53resolver:{self.region}:{ACCOUNT_ID}:resolver-endpoint/{self.id}" return f"arn:aws:route53resolver:{self.region}:{get_account_id()}:resolver-endpoint/{self.id}"
def _vpc_id_from_subnet(self): def _vpc_id_from_subnet(self):
"""Return VPC Id associated with the subnet. """Return VPC Id associated with the subnet.
@ -328,7 +328,7 @@ class Route53ResolverBackend(BaseBackend):
if len(associations) > ResolverRuleAssociation.MAX_RULE_ASSOCIATIONS_PER_REGION: if len(associations) > ResolverRuleAssociation.MAX_RULE_ASSOCIATIONS_PER_REGION:
# This error message was not verified to be the same for AWS. # This error message was not verified to be the same for AWS.
raise LimitExceededException( raise LimitExceededException(
f"Account '{ACCOUNT_ID}' has exceeded 'max-rule-association'" f"Account '{get_account_id()}' has exceeded 'max-rule-association'"
) )
if resolver_rule_id not in self.resolver_rules: if resolver_rule_id not in self.resolver_rules:
@ -448,7 +448,7 @@ class Route53ResolverBackend(BaseBackend):
endpoints = [x for x in self.resolver_endpoints.values() if x.region == region] endpoints = [x for x in self.resolver_endpoints.values() if x.region == region]
if len(endpoints) > ResolverEndpoint.MAX_ENDPOINTS_PER_REGION: if len(endpoints) > ResolverEndpoint.MAX_ENDPOINTS_PER_REGION:
raise LimitExceededException( raise LimitExceededException(
f"Account '{ACCOUNT_ID}' has exceeded 'max-endpoints'" f"Account '{get_account_id()}' has exceeded 'max-endpoints'"
) )
self._verify_subnet_ips(region, ip_addresses) self._verify_subnet_ips(region, ip_addresses)
@ -510,7 +510,7 @@ class Route53ResolverBackend(BaseBackend):
if len(rules) > ResolverRule.MAX_RULES_PER_REGION: if len(rules) > ResolverRule.MAX_RULES_PER_REGION:
# Did not verify that this is the actual error message. # Did not verify that this is the actual error message.
raise LimitExceededException( raise LimitExceededException(
f"Account '{ACCOUNT_ID}' has exceeded 'max-rules'" f"Account '{get_account_id()}' has exceeded 'max-rules'"
) )
# Per the AWS documentation and as seen with the AWS console, target # Per the AWS documentation and as seen with the AWS console, target

View File

@ -18,7 +18,7 @@ import uuid
from bisect import insort from bisect import insort
from importlib import reload from importlib import reload
from moto.core import ( from moto.core import (
ACCOUNT_ID, get_account_id,
BaseBackend, BaseBackend,
BaseModel, BaseModel,
CloudFormationModel, CloudFormationModel,
@ -78,9 +78,9 @@ OWNER = "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a"
def get_moto_s3_account_id(): def get_moto_s3_account_id():
"""This makes it easy for mocking AWS Account IDs when using AWS Config """This makes it easy for mocking AWS Account IDs when using AWS Config
-- Simply mock.patch the ACCOUNT_ID here, and Config gets it for free. -- Simply mock.patch get_account_id() here, and Config gets it for free.
""" """
return ACCOUNT_ID return get_account_id()
class FakeDeleteMarker(BaseModel): class FakeDeleteMarker(BaseModel):

View File

@ -15,7 +15,7 @@ import xmltodict
from moto.core.responses import _TemplateEnvironmentMixin, ActionAuthenticatorMixin from moto.core.responses import _TemplateEnvironmentMixin, ActionAuthenticatorMixin
from moto.core.utils import path_url from moto.core.utils import path_url
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.s3bucket_path.utils import ( from moto.s3bucket_path.utils import (
bucket_name_from_url as bucketpath_bucket_name_from_url, bucket_name_from_url as bucketpath_bucket_name_from_url,
@ -2446,7 +2446,7 @@ S3_ALL_MULTIPARTS = (
<UploadId>{{ upload.id }}</UploadId> <UploadId>{{ upload.id }}</UploadId>
<Initiator> <Initiator>
<ID>arn:aws:iam::""" <ID>arn:aws:iam::"""
+ ACCOUNT_ID + get_account_id()
+ """:user/user1-11111a31-17b5-4fb7-9df5-b111111f13de</ID> + """:user/user1-11111a31-17b5-4fb7-9df5-b111111f13de</ID>
<DisplayName>user1-11111a31-17b5-4fb7-9df5-b111111f13de</DisplayName> <DisplayName>user1-11111a31-17b5-4fb7-9df5-b111111f13de</DisplayName>
</Initiator> </Initiator>

View File

@ -1,6 +1,6 @@
from collections import defaultdict from collections import defaultdict
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import get_random_hex from moto.core.utils import get_random_hex
from moto.s3.exceptions import ( from moto.s3.exceptions import (
WrongPublicAccessBlockAccountIdError, WrongPublicAccessBlockAccountIdError,
@ -20,7 +20,7 @@ class AccessPoint(BaseModel):
self.alias = f"{name}-{get_random_hex(34)}-s3alias" self.alias = f"{name}-{get_random_hex(34)}-s3alias"
self.bucket = bucket self.bucket = bucket
self.created = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f") self.created = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
self.arn = f"arn:aws:s3:us-east-1:{ACCOUNT_ID}:accesspoint/{name}" self.arn = f"arn:aws:s3:us-east-1:{get_account_id()}:accesspoint/{name}"
self.policy = None self.policy = None
self.network_origin = "VPC" if vpc_configuration else "Internet" self.network_origin = "VPC" if vpc_configuration else "Internet"
self.vpc_id = (vpc_configuration or {}).get("VpcId") self.vpc_id = (vpc_configuration or {}).get("VpcId")
@ -55,7 +55,7 @@ class S3ControlBackend(BaseBackend):
def get_public_access_block(self, account_id): def get_public_access_block(self, account_id):
# The account ID should equal the account id that is set for Moto: # The account ID should equal the account id that is set for Moto:
if account_id != ACCOUNT_ID: if account_id != get_account_id():
raise WrongPublicAccessBlockAccountIdError() raise WrongPublicAccessBlockAccountIdError()
if not self.public_access_block: if not self.public_access_block:
@ -65,14 +65,14 @@ class S3ControlBackend(BaseBackend):
def delete_public_access_block(self, account_id): def delete_public_access_block(self, account_id):
# The account ID should equal the account id that is set for Moto: # The account ID should equal the account id that is set for Moto:
if account_id != ACCOUNT_ID: if account_id != get_account_id():
raise WrongPublicAccessBlockAccountIdError() raise WrongPublicAccessBlockAccountIdError()
self.public_access_block = None self.public_access_block = None
def put_public_access_block(self, account_id, pub_block_config): def put_public_access_block(self, account_id, pub_block_config):
# The account ID should equal the account id that is set for Moto: # The account ID should equal the account id that is set for Moto:
if account_id != ACCOUNT_ID: if account_id != get_account_id():
raise WrongPublicAccessBlockAccountIdError() raise WrongPublicAccessBlockAccountIdError()
if not pub_block_config: if not pub_block_config:

View File

@ -1,7 +1,7 @@
import json import json
import os import os
from datetime import datetime from datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel, CloudFormationModel from moto.core import get_account_id, BaseBackend, BaseModel, CloudFormationModel
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.sagemaker import validators from moto.sagemaker import validators
from moto.utilities.paginator import paginate from moto.utilities.paginator import paginate
@ -121,7 +121,7 @@ class FakeProcessingJob(BaseObject):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":processing-job/" + ":processing-job/"
+ endpoint_name + endpoint_name
) )
@ -230,7 +230,7 @@ class FakeTrainingJob(BaseObject):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":training-job/" + ":training-job/"
+ endpoint_name + endpoint_name
) )
@ -313,7 +313,7 @@ class FakeEndpoint(BaseObject, CloudFormationModel):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":endpoint/" + ":endpoint/"
+ endpoint_name + endpoint_name
) )
@ -503,7 +503,7 @@ class FakeEndpointConfig(BaseObject, CloudFormationModel):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":endpoint-config/" + ":endpoint-config/"
+ model_name + model_name
) )
@ -615,7 +615,7 @@ class Model(BaseObject, CloudFormationModel):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":model/" + ":model/"
+ model_name + model_name
) )
@ -819,7 +819,7 @@ class FakeSagemakerNotebookInstance(CloudFormationModel):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ self.region_name + self.region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":notebook-instance/" + ":notebook-instance/"
+ self.notebook_instance_name + self.notebook_instance_name
) )
@ -933,7 +933,7 @@ class FakeSageMakerNotebookInstanceLifecycleConfig(BaseObject, CloudFormationMod
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":notebook-instance-lifecycle-configuration/" + ":notebook-instance-lifecycle-configuration/"
+ notebook_instance_lifecycle_config_name + notebook_instance_lifecycle_config_name
) )
@ -1412,7 +1412,7 @@ class SageMakerModelBackend(BaseBackend):
self.trials[trial_name].trial_components.extend([trial_component_name]) self.trials[trial_name].trial_components.extend([trial_component_name])
else: else:
raise ResourceNotFound( raise ResourceNotFound(
message=f"Trial 'arn:aws:sagemaker:{self.region_name}:{ACCOUNT_ID}:experiment-trial/{trial_name}' does not exist." message=f"Trial 'arn:aws:sagemaker:{self.region_name}:{get_account_id()}:experiment-trial/{trial_name}' does not exist."
) )
if trial_component_name in self.trial_components.keys(): if trial_component_name in self.trial_components.keys():
@ -1441,8 +1441,8 @@ class SageMakerModelBackend(BaseBackend):
) )
return { return {
"TrialComponentArn": f"arn:aws:sagemaker:{self.region_name}:{ACCOUNT_ID}:experiment-trial-component/{trial_component_name}", "TrialComponentArn": f"arn:aws:sagemaker:{self.region_name}:{get_account_id()}:experiment-trial-component/{trial_component_name}",
"TrialArn": f"arn:aws:sagemaker:{self.region_name}:{ACCOUNT_ID}:experiment-trial/{trial_name}", "TrialArn": f"arn:aws:sagemaker:{self.region_name}:{get_account_id()}:experiment-trial/{trial_name}",
} }
def create_notebook_instance( def create_notebook_instance(
@ -2003,7 +2003,7 @@ class FakeExperiment(BaseObject):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":experiment/" + ":experiment/"
+ experiment_arn + experiment_arn
) )
@ -2039,7 +2039,7 @@ class FakeTrial(BaseObject):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":experiment-trial/" + ":experiment-trial/"
+ trial_name + trial_name
) )
@ -2073,7 +2073,7 @@ class FakeTrialComponent(BaseObject):
"arn:aws:sagemaker:" "arn:aws:sagemaker:"
+ region_name + region_name
+ ":" + ":"
+ str(ACCOUNT_ID) + str(get_account_id())
+ ":experiment-trial-component/" + ":experiment-trial-component/"
+ trial_component_name + trial_component_name
) )

View File

@ -2,7 +2,7 @@ import random
import string import string
import re import re
from moto.core import ACCOUNT_ID from moto.core import get_account_id
def random_password( def random_password(
@ -66,7 +66,7 @@ def random_password(
def secret_arn(region, secret_id): def secret_arn(region, secret_id):
id_string = "".join(random.choice(string.ascii_letters) for _ in range(5)) id_string = "".join(random.choice(string.ascii_letters) for _ in range(5))
return "arn:aws:secretsmanager:{0}:{1}:secret:{2}-{3}".format( return "arn:aws:secretsmanager:{0}:{1}:secret:{2}-{3}".format(
region, ACCOUNT_ID, secret_id, id_string region, get_account_id(), secret_id, id_string
) )

View File

@ -1,7 +1,7 @@
import random import random
import string import string
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.utils import BackendDict, unix_time from moto.core.utils import BackendDict, unix_time
from moto.utilities.tagging_service import TaggingService from moto.utilities.tagging_service import TaggingService
@ -33,7 +33,9 @@ class Namespace(BaseModel):
): ):
super().__init__() super().__init__()
self.id = f"ns-{random_id(20)}" self.id = f"ns-{random_id(20)}"
self.arn = f"arn:aws:servicediscovery:{region}:{ACCOUNT_ID}:namespace/{self.id}" self.arn = (
f"arn:aws:servicediscovery:{region}:{get_account_id()}:namespace/{self.id}"
)
self.name = name self.name = name
self.type = ns_type self.type = ns_type
self.creator_request_id = creator_request_id self.creator_request_id = creator_request_id
@ -76,7 +78,9 @@ class Service(BaseModel):
): ):
super().__init__() super().__init__()
self.id = f"srv-{random_id(8)}" self.id = f"srv-{random_id(8)}"
self.arn = f"arn:aws:servicediscovery:{region}:{ACCOUNT_ID}:service/{self.id}" self.arn = (
f"arn:aws:servicediscovery:{region}:{get_account_id()}:service/{self.id}"
)
self.name = name self.name = name
self.namespace_id = namespace_id self.namespace_id = namespace_id
self.description = description self.description = description

View File

@ -1,4 +1,4 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
""" """
SES Feedback messages SES Feedback messages
@ -12,7 +12,7 @@ COMMON_MAIL = {
"source": "sender@example.com", "source": "sender@example.com",
"sourceArn": "arn:aws:ses:us-west-2:888888888888:identity/example.com", "sourceArn": "arn:aws:ses:us-west-2:888888888888:identity/example.com",
"sourceIp": "127.0.3.0", "sourceIp": "127.0.3.0",
"sendingAccountId": ACCOUNT_ID, "sendingAccountId": get_account_id(),
"destination": ["recipient@example.com"], "destination": ["recipient@example.com"],
"headersTruncated": False, "headersTruncated": False,
"headers": [ "headers": [

View File

@ -30,7 +30,7 @@ from .exceptions import (
) )
from .utils import make_arn_for_topic, make_arn_for_subscription, is_e164 from .utils import make_arn_for_topic, make_arn_for_subscription, is_e164
from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.core import get_account_id
DEFAULT_PAGE_SIZE = 100 DEFAULT_PAGE_SIZE = 100
MAXIMUM_MESSAGE_LENGTH = 262144 # 256 KiB MAXIMUM_MESSAGE_LENGTH = 262144 # 256 KiB
@ -41,7 +41,7 @@ class Topic(CloudFormationModel):
def __init__(self, name, sns_backend): def __init__(self, name, sns_backend):
self.name = name self.name = name
self.sns_backend = sns_backend self.sns_backend = sns_backend
self.account_id = DEFAULT_ACCOUNT_ID self.account_id = get_account_id()
self.display_name = "" self.display_name = ""
self.delivery_policy = "" self.delivery_policy = ""
self.kms_master_key_id = "" self.kms_master_key_id = ""
@ -142,7 +142,7 @@ class Topic(CloudFormationModel):
topic_name = properties.get(cls.cloudformation_name_type()) or resource_name topic_name = properties.get(cls.cloudformation_name_type()) or resource_name
topic_arn = make_arn_for_topic( topic_arn = make_arn_for_topic(
DEFAULT_ACCOUNT_ID, topic_name, sns_backend.region_name get_account_id(), topic_name, sns_backend.region_name
) )
subscriptions, _ = sns_backend.list_subscriptions(topic_arn) subscriptions, _ = sns_backend.list_subscriptions(topic_arn)
for subscription in subscriptions: for subscription in subscriptions:
@ -334,7 +334,7 @@ class Subscription(BaseModel):
"Signature": "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=", "Signature": "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=",
"SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem", "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",
"UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:{}:some-topic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55".format( "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:{}:some-topic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55".format(
DEFAULT_ACCOUNT_ID get_account_id()
), ),
} }
if subject: if subject:
@ -357,7 +357,7 @@ class PlatformApplication(BaseModel):
region=self.region, region=self.region,
platform=self.platform, platform=self.platform,
name=self.name, name=self.name,
AccountId=DEFAULT_ACCOUNT_ID, AccountId=get_account_id(),
) )
@ -392,7 +392,7 @@ class PlatformEndpoint(BaseModel):
return ( return (
"arn:aws:sns:{region}:{AccountId}:endpoint/{platform}/{name}/{id}".format( "arn:aws:sns:{region}:{AccountId}:endpoint/{platform}/{name}/{id}".format(
region=self.region, region=self.region,
AccountId=DEFAULT_ACCOUNT_ID, AccountId=get_account_id(),
platform=self.application.platform, platform=self.application.platform,
name=self.application.name, name=self.application.name,
id=self.id, id=self.id,
@ -558,7 +558,7 @@ class SNSBackend(BaseBackend):
"TopicArn": topic_arn, "TopicArn": topic_arn,
"Protocol": protocol, "Protocol": protocol,
"SubscriptionArn": subscription.arn, "SubscriptionArn": subscription.arn,
"Owner": DEFAULT_ACCOUNT_ID, "Owner": get_account_id(),
"RawMessageDelivery": "false", "RawMessageDelivery": "false",
} }

View File

@ -37,7 +37,7 @@ from .exceptions import (
InvalidAttributeValue, InvalidAttributeValue,
) )
from moto.core import ACCOUNT_ID from moto.core import get_account_id
DEFAULT_SENDER_ID = "AIDAIT2UOQQY3AUEKVGXU" DEFAULT_SENDER_ID = "AIDAIT2UOQQY3AUEKVGXU"
@ -262,7 +262,7 @@ class Queue(CloudFormationModel):
now = unix_time() now = unix_time()
self.created_timestamp = now self.created_timestamp = now
self.queue_arn = "arn:aws:sqs:{0}:{1}:{2}".format( self.queue_arn = "arn:aws:sqs:{0}:{1}:{2}".format(
self.region, ACCOUNT_ID, self.name self.region, get_account_id(), self.name
) )
self.dead_letter_queue = None self.dead_letter_queue = None
@ -474,7 +474,7 @@ class Queue(CloudFormationModel):
@property @property
def physical_resource_id(self): def physical_resource_id(self):
return f"https://sqs.{self.region}.amazonaws.com/{ACCOUNT_ID}/{self.name}" return f"https://sqs.{self.region}.amazonaws.com/{get_account_id()}/{self.name}"
@property @property
def attributes(self): def attributes(self):
@ -508,7 +508,7 @@ class Queue(CloudFormationModel):
def url(self, request_url): def url(self, request_url):
return "{0}://{1}/{2}/{3}".format( return "{0}://{1}/{2}/{3}".format(
request_url.scheme, request_url.netloc, ACCOUNT_ID, self.name request_url.scheme, request_url.netloc, get_account_id(), self.name
) )
@property @property

View File

@ -4,7 +4,7 @@ from typing import Dict
from collections import defaultdict from collections import defaultdict
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core import get_account_id, BaseBackend, BaseModel
from moto.core.exceptions import RESTError from moto.core.exceptions import RESTError
from moto.core.utils import BackendDict from moto.core.utils import BackendDict
from moto.ec2 import ec2_backends from moto.ec2 import ec2_backends
@ -395,7 +395,7 @@ class Document(BaseModel):
self.status = "Active" self.status = "Active"
self.document_version = document_version self.document_version = document_version
self.owner = ACCOUNT_ID self.owner = get_account_id()
self.created_date = datetime.datetime.utcnow() self.created_date = datetime.datetime.utcnow()
if document_format == "JSON": if document_format == "JSON":
@ -695,7 +695,7 @@ def _document_filter_match(filters, ssm_doc):
raise ValidationException("Owner filter can only have one value.") raise ValidationException("Owner filter can only have one value.")
if _filter["Values"][0] == "Self": if _filter["Values"][0] == "Self":
# Update to running account ID # Update to running account ID
_filter["Values"][0] = ACCOUNT_ID _filter["Values"][0] = get_account_id()
if not _document_filter_equal_comparator(ssm_doc.owner, _filter): if not _document_filter_equal_comparator(ssm_doc.owner, _filter):
return False return False

View File

@ -1,11 +1,11 @@
from moto.core import ACCOUNT_ID from moto.core import get_account_id
def parameter_arn(region, parameter_name): def parameter_arn(region, parameter_name):
if parameter_name[0] == "/": if parameter_name[0] == "/":
parameter_name = parameter_name[1:] parameter_name = parameter_name[1:]
return "arn:aws:ssm:{0}:{1}:parameter/{2}".format( return "arn:aws:ssm:{0}:{1}:parameter/{2}".format(
region, ACCOUNT_ID, parameter_name region, get_account_id(), parameter_name
) )

View File

@ -3,7 +3,7 @@ import re
from datetime import datetime from datetime import datetime
from dateutil.tz import tzlocal from dateutil.tz import tzlocal
from moto.core import ACCOUNT_ID, BaseBackend, CloudFormationModel from moto.core import get_account_id, BaseBackend, CloudFormationModel
from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict
from uuid import uuid4 from uuid import uuid4
from .exceptions import ( from .exceptions import (
@ -619,7 +619,7 @@ class StepFunctionBackend(BaseBackend):
return self.describe_state_machine(state_machine_arn) return self.describe_state_machine(state_machine_arn)
def _get_account_id(self): def _get_account_id(self):
return ACCOUNT_ID return get_account_id()
stepfunction_backends = BackendDict(StepFunctionBackend, "stepfunctions") stepfunction_backends = BackendDict(StepFunctionBackend, "stepfunctions")

View File

@ -3,7 +3,7 @@ import datetime
import xmltodict import xmltodict
from moto.core import BaseBackend, BaseModel from moto.core import BaseBackend, BaseModel
from moto.core.utils import iso_8601_datetime_with_milliseconds from moto.core.utils import iso_8601_datetime_with_milliseconds
from moto.core import ACCOUNT_ID from moto.core import get_account_id
from moto.sts.utils import ( from moto.sts.utils import (
random_access_key_id, random_access_key_id,
random_secret_access_key, random_secret_access_key,
@ -50,7 +50,7 @@ class AssumedRole(BaseModel):
def arn(self): def arn(self):
return ( return (
"arn:aws:sts::{account_id}:assumed-role/{role_name}/{session_name}".format( "arn:aws:sts::{account_id}:assumed-role/{role_name}/{session_name}".format(
account_id=ACCOUNT_ID, account_id=get_account_id(),
role_name=self.role_arn.split("/")[-1], role_name=self.role_arn.split("/")[-1],
session_name=self.session_name, session_name=self.session_name,
) )

Some files were not shown because too many files have changed in this diff Show More