Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(appconfig): support predefined deployment strategies (#1986)

koh-sh2e769a6dc50e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e0744ada..2ab1cefa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **AppConfig — predefined deployment strategies** — `AppConfig.AllAtOnce`, `AppConfig.Linear50PercentEvery30Seconds`, `AppConfig.Canary10Percent20Minutes` and `AppConfig.Linear20PercentEvery6Minutes` now exist in every account and region and cannot be updated or deleted, as on AWS. A deployment records its strategy's parameters, and `StartDeployment` and `AWS::AppConfig::Deployment` fail with `ResourceNotFoundException` for a strategy that does not exist, where they used to accept any id. Contributed by @koh-sh.
- **RDS — standalone deletion protection and snapshot-tag settings apply immediately** — `ModifyDBInstance` now applies `DeletionProtection` and `CopyTagsToSnapshot` regardless of `ApplyImmediately`, returning the active values without adding these fields to `PendingModifiedValues`. Omitted settings keep their existing values.
- **OpenSearch — data-plane containers are named per account** — a domain's container was named `ministack-opensearch-<region>-<domain>`, so a second account creating a domain of the same name (including an account on another MiniStack sharing the Docker daemon) failed with a Docker name conflict, and the failed create's cleanup removed containers by that name. The names now carry an account and region hash, as RDS's do. Contributed by @skialpine.
- **RDS — a MySQL master user started in the background keeps its admin grant** — an instance whose engine image was not cached yet, or one respawned on restore, started on a background path that skipped the master-user grant the inline path gives, so the master user held only its own database and `SET PERSIST` failed for lack of `SYSTEM_VARIABLES_ADMIN`. Both paths now grant it. Contributed by @skialpine.
diff --git a/README.md b/README.md
index 4b89bf50..915bd695 100644
--- a/README.md
+++ b/README.md
@@ -628,7 +628,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **S3 Files** | CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem, CreateMountTarget, GetMountTarget, ListMountTargets, UpdateMountTarget, DeleteMountTarget, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, GetFileSystemPolicy, PutFileSystemPolicy, DeleteFileSystemPolicy, GetSynchronizationConfiguration, PutSynchronizationConfiguration, TagResource, UntagResource, ListTagsForResource | 21 operations; control plane for the new S3 Files service (launched April 2026); file systems, mount targets, access points, policies |
| **AutoScaling** | CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup, DeleteAutoScalingGroup, SetDesiredCapacity, DescribeAutoScalingInstances, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, PutScalingPolicy, DescribePolicies, DeletePolicy, PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook, CompleteLifecycleAction, RecordLifecycleActionHeartbeat, PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction, CreateOrUpdateTags, DescribeTags, DeleteTags | 24 actions; in-memory state — no real instances, but groups report `DesiredCapacity` in-service instances so Terraform's `aws_autoscaling_group` capacity waiter converges; full ASG lifecycle (launch configs, scaling policies, lifecycle hooks, scheduled actions, tags); CDK/Terraform compatible |
| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back |
-| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; deployments complete immediately; session-based configuration retrieval with token rotation |
+| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments complete immediately; session-based configuration retrieval with token rotation |
| **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |
| **IoT Jobs** | Control plane (`iot`): CreateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 9 control-plane + 4 device data-plane operations sharing one store. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |
| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations | 56 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry |
diff --git a/ministack/services/appconfig.py b/ministack/services/appconfig.py
index 7d996f83..e026c522 100644
--- a/ministack/services/appconfig.py
+++ b/ministack/services/appconfig.py
@@ -457,6 +457,40 @@ def _delete_hosted_configuration_version(app_id, profile_id, version_number):
# ---------------------------------------------------------------------------
+def _predefined_strategy(strategy_id, fields):
+ """A predefined strategy record; AWS names it by its id."""
+ return {
+ "Id": strategy_id,
+ "Name": strategy_id,
+ **fields,
+ "ReplicateTo": "NONE",
+ }
+
+
+# Values as ListDeploymentStrategies returns them on AWS.
+_PREDEFINED_DEPLOYMENT_STRATEGIES = {
+ strategy_id: _predefined_strategy(strategy_id, fields)
+ for strategy_id, fields in {
+ "AppConfig.AllAtOnce": {
+ "Description": "Quick", "DeploymentDurationInMinutes": 0, "GrowthType": "LINEAR",
+ "GrowthFactor": 100.0, "FinalBakeTimeInMinutes": 10,
+ },
+ "AppConfig.Linear50PercentEvery30Seconds": {
+ "Description": "Test/Demo", "DeploymentDurationInMinutes": 1, "GrowthType": "LINEAR",
+ "GrowthFactor": 50.0, "FinalBakeTimeInMinutes": 1,
+ },
+ "AppConfig.Canary10Percent20Minutes": {
+ "Description": "AWS Recommended", "DeploymentDurationInMinutes": 20, "GrowthType": "EXPONENTIAL",
+ "GrowthFactor": 10.0, "FinalBakeTimeInMinutes": 10,
+ },
+ "AppConfig.Linear20PercentEvery6Minutes": {
+ "Description": "AWS Recommended", "DeploymentDurationInMinutes": 30, "GrowthType": "LINEAR",
+ "GrowthFactor": 20.0, "FinalBakeTimeInMinutes": 30,
+ },
+ }.items()
+}
+
+
def _create_deployment_strategy(body):
name = body.get("Name")
if not name:
@@ -478,8 +512,23 @@ def _create_deployment_strategy(body):
return _json(201, record)
+def _find_deployment_strategy(strategy_id):
+ """A stored strategy of this account and region, or else the predefined one with that id."""
+ return _deployment_strategies.get(strategy_id) or _PREDEFINED_DEPLOYMENT_STRATEGIES.get(strategy_id)
+
+
+def _deployment_params_from_strategy(strategy):
+ """The strategy fields a deployment copies when it starts; later strategy changes do not reach it."""
+ return {
+ "DeploymentDurationInMinutes": strategy["DeploymentDurationInMinutes"],
+ "GrowthType": strategy["GrowthType"],
+ "GrowthFactor": strategy["GrowthFactor"],
+ "FinalBakeTimeInMinutes": strategy["FinalBakeTimeInMinutes"],
+ }
+
+
def _get_deployment_strategy(strategy_id):
- strategy = _deployment_strategies.get(strategy_id)
+ strategy = _find_deployment_strategy(strategy_id)
if not strategy:
return _error(404, "ResourceNotFoundException", f"Deployment strategy {strategy_id} not found")
return _json(200, strategy)
@@ -487,11 +536,13 @@ def _get_deployment_strategy(strategy_id):
def _list_deployment_strategies(query):
max_results = int(query.get("max_results", 50))
- items = list(_deployment_strategies.values())
+ items = [*_deployment_strategies.values(), *_PREDEFINED_DEPLOYMENT_STRATEGIES.values()]
return _json(200, {"Items": items[:max_results]})
def _update_deployment_strategy(strategy_id, body):
+ if strategy_id in _PREDEFINED_DEPLOYMENT_STRATEGIES:
+ return _error(400, "BadRequestException", f"Cannot update predefined Deployment Strategy {strategy_id}")
strategy = _deployment_strategies.get(strategy_id)
if not strategy:
return _error(404, "ResourceNotFoundException", f"Deployment strategy {strategy_id} not found")
@@ -503,6 +554,9 @@ def _update_deployment_strategy(strategy_id, body):
def _delete_deployment_strategy(strategy_id):
+ # AWS ends this message with a period; the update message has none.
+ if strategy_id in _PREDEFINED_DEPLOYMENT_STRATEGIES:
+ return _error(400, "BadRequestException", f"Cannot delete predefined Deployment Strategy {strategy_id}.")
if strategy_id not in _deployment_strategies:
return _error(404, "ResourceNotFoundException", f"Deployment strategy {strategy_id} not found")
del _deployment_strategies[strategy_id]
@@ -528,6 +582,11 @@ def _start_deployment(app_id, env_id, body):
if profile_id and f"{app_id}/{profile_id}" not in _config_profiles:
return _error(404, "ResourceNotFoundException", f"Configuration profile {profile_id} not found")
+ strategy = _find_deployment_strategy(strategy_id)
+ if not strategy:
+ return _error(404, "ResourceNotFoundException",
+ f"DeploymentStrategy with Id {strategy_id} could not be found.")
+
existing = [
v for k, v in _deployments.items()
if k.startswith(f"{app_id}/{env_id}/")
@@ -545,10 +604,7 @@ def _start_deployment(app_id, env_id, body):
"ConfigurationLocationUri": "hosted",
"ConfigurationVersion": version,
"Description": body.get("Description", ""),
- "DeploymentDurationInMinutes": 0,
- "GrowthType": "LINEAR",
- "GrowthFactor": 100.0,
- "FinalBakeTimeInMinutes": 0,
+ **_deployment_params_from_strategy(strategy),
"State": "COMPLETE",
"PercentageComplete": 100.0,
"StartedAt": now,
@@ -661,7 +717,7 @@ def _resolve_tag_resource_arn(resource_arn):
return None, _missing_tag_resource(resource_arn)
if len(parts) == 2 and parts[0] == "deploymentstrategy" and parts[1]:
- if parts[1] in _deployment_strategies:
+ if _find_deployment_strategy(parts[1]):
return str(spec), None
return None, _missing_tag_resource(resource_arn)
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 1775abb8..c51e42a5 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -3151,6 +3151,9 @@ def _appconfig_deployment_create(logical_id, props, stack_name):
"AWS::AppConfig::Deployment requires ApplicationId, EnvironmentId, "
"DeploymentStrategyId, and ConfigurationProfileId"
)
+ strategy = _appconfig._find_deployment_strategy(strategy_id)
+ if not strategy:
+ raise ValueError(f"DeploymentStrategy with Id {strategy_id} could not be found.")
existing = [
v for k, v in _appconfig._deployments.items()
if k.startswith(f"{app_id}/{env_id}/")
@@ -3169,6 +3172,7 @@ def _appconfig_deployment_create(logical_id, props, stack_name):
"ConfigurationLocationUri": "hosted",
"ConfigurationVersion": props.get("ConfigurationVersion", ""),
"Description": props.get("Description", ""),
+ **_appconfig._deployment_params_from_strategy(strategy),
"State": "COMPLETE",
"PercentageComplete": 100.0,
"StartedAt": now,
diff --git a/tests/test_appconfig.py b/tests/test_appconfig.py
index a8f97849..e71827aa 100644
--- a/tests/test_appconfig.py
+++ b/tests/test_appconfig.py
@@ -411,6 +411,78 @@ def test_appconfig_delete_deployment_strategy(appconfig_client):
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+# As ListDeploymentStrategies returned them on AWS, in AWS's order.
+_AWS_PREDEFINED_STRATEGIES = [
+ {"Id": "AppConfig.AllAtOnce", "Name": "AppConfig.AllAtOnce", "Description": "Quick",
+ "DeploymentDurationInMinutes": 0, "GrowthType": "LINEAR", "GrowthFactor": 100.0,
+ "FinalBakeTimeInMinutes": 10, "ReplicateTo": "NONE"},
+ {"Id": "AppConfig.Linear50PercentEvery30Seconds", "Name": "AppConfig.Linear50PercentEvery30Seconds",
+ "Description": "Test/Demo", "DeploymentDurationInMinutes": 1, "GrowthType": "LINEAR",
+ "GrowthFactor": 50.0, "FinalBakeTimeInMinutes": 1, "ReplicateTo": "NONE"},
+ {"Id": "AppConfig.Canary10Percent20Minutes", "Name": "AppConfig.Canary10Percent20Minutes",
+ "Description": "AWS Recommended", "DeploymentDurationInMinutes": 20, "GrowthType": "EXPONENTIAL",
+ "GrowthFactor": 10.0, "FinalBakeTimeInMinutes": 10, "ReplicateTo": "NONE"},
+ {"Id": "AppConfig.Linear20PercentEvery6Minutes", "Name": "AppConfig.Linear20PercentEvery6Minutes",
+ "Description": "AWS Recommended", "DeploymentDurationInMinutes": 30, "GrowthType": "LINEAR",
+ "GrowthFactor": 20.0, "FinalBakeTimeInMinutes": 30, "ReplicateTo": "NONE"},
+]
+
+
+def _strategy_fields(response):
+ return {k: v for k, v in response.items() if k != "ResponseMetadata"}
+
+
+def test_appconfig_get_predefined_deployment_strategies(appconfig_client):
+ for expected in _AWS_PREDEFINED_STRATEGIES:
+ resp = appconfig_client.get_deployment_strategy(DeploymentStrategyId=expected["Id"])
+ assert _strategy_fields(resp) == expected
+
+
+def test_appconfig_list_deployment_strategies_puts_predefined_after_own(appconfig_service_state):
+ status, created = _status_and_body(
+ appconfig_service._create_deployment_strategy({"Name": "own-strategy", "ReplicateTo": "NONE"})
+ )
+ assert status == 201
+ status, body = _status_and_body(appconfig_service._list_deployment_strategies({}))
+ assert status == 200
+ assert [s["Id"] for s in body["Items"]] == [
+ created["Id"],
+ "AppConfig.AllAtOnce",
+ "AppConfig.Linear50PercentEvery30Seconds",
+ "AppConfig.Canary10Percent20Minutes",
+ "AppConfig.Linear20PercentEvery6Minutes",
+ ]
+
+
+def test_appconfig_predefined_deployment_strategy_cannot_be_updated(appconfig_client):
+ strategy_id = "AppConfig.AllAtOnce"
+ with pytest.raises(ClientError) as exc:
+ appconfig_client.update_deployment_strategy(DeploymentStrategyId=strategy_id, Description="changed")
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Message"] == f"Cannot update predefined Deployment Strategy {strategy_id}"
+ resp = appconfig_client.get_deployment_strategy(DeploymentStrategyId=strategy_id)
+ assert _strategy_fields(resp) == _AWS_PREDEFINED_STRATEGIES[0]
+
+
+def test_appconfig_predefined_deployment_strategy_cannot_be_deleted(appconfig_client):
+ strategy_id = "AppConfig.AllAtOnce"
+ with pytest.raises(ClientError) as exc:
+ appconfig_client.delete_deployment_strategy(DeploymentStrategyId=strategy_id)
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Message"] == f"Cannot delete predefined Deployment Strategy {strategy_id}."
+ resp = appconfig_client.get_deployment_strategy(DeploymentStrategyId=strategy_id)
+ assert _strategy_fields(resp) == _AWS_PREDEFINED_STRATEGIES[0]
+
+
+def test_appconfig_predefined_deployment_strategies_stay_out_of_saved_state(appconfig_service_state):
+ status, body = _status_and_body(appconfig_service._get_deployment_strategy("AppConfig.AllAtOnce"))
+ assert status == 200
+ assert body["Id"] == "AppConfig.AllAtOnce"
+ assert not appconfig_service.get_state()["deployment_strategies"]
+
+
# ---------------------------------------------------------------------------
# Deployments
# ---------------------------------------------------------------------------
@@ -532,6 +604,65 @@ def test_appconfig_stop_deployment(appconfig_client):
assert resp["State"] == "ROLLED_BACK"
+def _deployment_target(appconfig_client, name):
+ app = appconfig_client.create_application(Name=name)
+ env = appconfig_client.create_environment(ApplicationId=app["Id"], Name="env")
+ profile = appconfig_client.create_configuration_profile(
+ ApplicationId=app["Id"], Name="profile", LocationUri="hosted",
+ )
+ appconfig_client.create_hosted_configuration_version(
+ ApplicationId=app["Id"], ConfigurationProfileId=profile["Id"],
+ Content=b"{}", ContentType="application/json",
+ )
+ return {"ApplicationId": app["Id"], "EnvironmentId": env["Id"]}, profile["Id"]
+
+
+def _rollout_params(deployment):
+ return (deployment["DeploymentDurationInMinutes"], deployment["GrowthType"],
+ deployment["GrowthFactor"], deployment["FinalBakeTimeInMinutes"])
+
+
+def test_appconfig_start_deployment_records_predefined_strategy_parameters(appconfig_client):
+ ids, profile_id = _deployment_target(appconfig_client, "deploy-predefined-app")
+ deploy = appconfig_client.start_deployment(
+ **ids, DeploymentStrategyId="AppConfig.Canary10Percent20Minutes",
+ ConfigurationProfileId=profile_id, ConfigurationVersion="1",
+ )
+ assert deploy["DeploymentStrategyId"] == "AppConfig.Canary10Percent20Minutes"
+ got = appconfig_client.get_deployment(**ids, DeploymentNumber=deploy["DeploymentNumber"])
+ listed = appconfig_client.list_deployments(**ids)["Items"][0]
+ for record in (deploy, got, listed):
+ assert _rollout_params(record) == (20, "EXPONENTIAL", 10.0, 10)
+
+
+def test_appconfig_start_deployment_records_own_strategy_parameters(appconfig_client):
+ ids, profile_id = _deployment_target(appconfig_client, "deploy-own-strategy-app")
+ strategy = appconfig_client.create_deployment_strategy(
+ Name="own-params", DeploymentDurationInMinutes=5, GrowthType="LINEAR",
+ GrowthFactor=25.0, FinalBakeTimeInMinutes=3, ReplicateTo="NONE",
+ )
+ deploy = appconfig_client.start_deployment(
+ **ids, DeploymentStrategyId=strategy["Id"],
+ ConfigurationProfileId=profile_id, ConfigurationVersion="1",
+ )
+ assert _rollout_params(deploy) == (5, "LINEAR", 25.0, 3)
+
+
+def test_appconfig_start_deployment_rejects_missing_strategy(appconfig_client):
+ ids, profile_id = _deployment_target(appconfig_client, "deploy-missing-strategy-app")
+ for strategy_id in ("abcdefg", "AppConfig.DoesNotExist"):
+ with pytest.raises(ClientError) as exc:
+ appconfig_client.start_deployment(
+ **ids, DeploymentStrategyId=strategy_id,
+ ConfigurationProfileId=profile_id, ConfigurationVersion="1",
+ )
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Message"] == (
+ f"DeploymentStrategy with Id {strategy_id} could not be found.")
+ assert appconfig_client.list_deployments(**ids)["Items"] == []
+
+
# ---------------------------------------------------------------------------
# Tags
# ---------------------------------------------------------------------------
@@ -882,6 +1013,23 @@ def test_appconfig_applications_are_region_scoped():
pass
+def test_appconfig_predefined_deployment_strategy_tags_are_region_scoped():
+ """Tags on a predefined strategy belong to the account and region that set them."""
+ east = _make_appconfig_client("us-east-1")
+ west = _make_appconfig_client("us-west-2")
+ strategy_id = "AppConfig.Linear20PercentEvery6Minutes"
+ east_arn = f"arn:aws:appconfig:us-east-1:000000000000:deploymentstrategy/{strategy_id}"
+ west_arn = f"arn:aws:appconfig:us-west-2:000000000000:deploymentstrategy/{strategy_id}"
+
+ east.tag_resource(ResourceArn=east_arn, Tags={"probe": "east"})
+ try:
+ assert east.list_tags_for_resource(ResourceArn=east_arn)["Tags"] == {"probe": "east"}
+ assert west.list_tags_for_resource(ResourceArn=west_arn)["Tags"] == {}
+ finally:
+ east.untag_resource(ResourceArn=east_arn, TagKeys=["probe"])
+ assert east.list_tags_for_resource(ResourceArn=east_arn)["Tags"] == {}
+
+
def _deploy_and_fetch(appconfig_client, appconfigdata_client, profile_type, content,
suffix):
"""Create app/env/profile, deploy `content`, and return the served bytes."""
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index c6a7fb34..dddd60db 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -28367,6 +28367,61 @@ def test_cfn_appconfig_deployment_replacement_keeps_the_old_deployment(cfn, appc
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+def _cfn_appconfig_deployment_template(name, strategy_id):
+ """An application, environment, profile, hosted version and a deployment with `strategy_id`."""
+ return json.dumps({
+ "Resources": {
+ "App": {"Type": "AWS::AppConfig::Application", "Properties": {"Name": name}},
+ "Env": {"Type": "AWS::AppConfig::Environment", "Properties": {
+ "ApplicationId": {"Ref": "App"}, "Name": name}},
+ "Profile": {"Type": "AWS::AppConfig::ConfigurationProfile", "Properties": {
+ "ApplicationId": {"Ref": "App"}, "Name": name, "LocationUri": "hosted"}},
+ "HCV": {"Type": "AWS::AppConfig::HostedConfigurationVersion", "Properties": {
+ "ApplicationId": {"Ref": "App"}, "ConfigurationProfileId": {"Ref": "Profile"},
+ "ContentType": "application/json", "Content": "{}"}},
+ "Deployment": {"Type": "AWS::AppConfig::Deployment", "Properties": {
+ "ApplicationId": {"Ref": "App"}, "EnvironmentId": {"Ref": "Env"},
+ "ConfigurationProfileId": {"Ref": "Profile"},
+ "DeploymentStrategyId": strategy_id,
+ "ConfigurationVersion": {"Ref": "HCV"}}},
+ },
+ "Outputs": {"AppId": {"Value": {"Ref": "App"}},
+ "EnvId": {"Value": {"Ref": "Env"}},
+ "Number": {"Value": {"Fn::GetAtt": ["Deployment", "DeploymentNumber"]}}},
+ })
+
+
+def test_cfn_appconfig_deployment_with_a_predefined_strategy(cfn, appconfig_client):
+ """The deployment records the parameters of the predefined strategy it names."""
+ stack_name = f"cfn-ac-predef-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_appconfig_deployment_template(stack_name, "AppConfig.AllAtOnce"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ deployment = appconfig_client.get_deployment(
+ ApplicationId=_cfn_output(cfn, stack_name, "AppId"),
+ EnvironmentId=_cfn_output(cfn, stack_name, "EnvId"),
+ DeploymentNumber=int(_cfn_output(cfn, stack_name, "Number")))
+ assert deployment["DeploymentStrategyId"] == "AppConfig.AllAtOnce"
+ assert (deployment["DeploymentDurationInMinutes"], deployment["GrowthType"],
+ deployment["GrowthFactor"], deployment["FinalBakeTimeInMinutes"]) == (0, "LINEAR", 100.0, 10)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_appconfig_deployment_with_a_missing_strategy_rolls_back(cfn):
+ """A deployment naming a strategy that does not exist fails and rolls the stack back."""
+ stack_name = f"cfn-ac-nostrat-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_appconfig_deployment_template(stack_name, "abcdefg"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ assert "DeploymentStrategy with Id abcdefg could not be found." in _stack_event_reasons(cfn, stack_name)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_appsync_api_update_keeps_id_and_children(cfn, appsync):
"""A GraphQL API update keeps its id and its data sources."""
suffix = _uuid_mod.uuid4().hex[:8]