ecs_deploy 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7ada66f2f084f7ea0e30b0b6808d2635480db1071ae13acfc16f6f7d4cc02fef
4
- data.tar.gz: 2188aa1ed3727d1c7719bca93006383b831a6f6379ffa28b08aee8a97d5281e5
3
+ metadata.gz: b9c9790c06b5e223cc9f66ec7236d5f90b3c63d0822a6783660db0a5ec8fe9f4
4
+ data.tar.gz: 0b8b43d3279c5b7a1aca5eb50015b9227fdad61aeeaa7fc86162c41f2cc7691f
5
5
  SHA512:
6
- metadata.gz: a3e3f662af6586e71f002853a3599adb107c7db5b8b44c4d7ce3d8d13c6d37ae2210ec9a0a0749813e926f78c4879a3a72d851f6dfd2c466e8ec296a9900f244
7
- data.tar.gz: f96818f250b0644a3908822fa741b26bba564095feff3d78e9a28acc30baa9da5b435200d3c2bc83edf4a2e3e7b73e48e5702ade9f1f3ac7c614be1a9402a067
6
+ metadata.gz: a15a864308abd8534440dc0aa0b25555c43d833495c2b233c618e9d0bd748209ec2a943c595b163ebbb117a114ae8051116b92d85162c7465dfab6673ed38d29
7
+ data.tar.gz: f00be63c2df0578018519614bf4d20525fce8375ea6c47c90d8572bbc2a0a2f362d11d53b46e197711512b7d78834cfc94d943241f2c35f83e7a253590d54174
@@ -12,9 +12,9 @@ jobs:
12
12
  ruby-version: ["3.2", "3.3", "3.4", "4.0"]
13
13
 
14
14
  steps:
15
- - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
15
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
16
16
  - name: Set up Ruby
17
- uses: ruby/setup-ruby@0dafeac902942906541bc140009cdbf32665b601 # v1.315.0
17
+ uses: ruby/setup-ruby@v1
18
18
  with:
19
19
  ruby-version: ${{ matrix.ruby-version }}
20
20
  bundler-cache: true
data/CHANGELOG.md CHANGED
@@ -5,6 +5,7 @@
5
5
  ### New feature
6
6
 
7
7
  - Add `ecs:describe_deployment`, `ecs:continue_deployment[hook_id]`, `ecs:rollback_deployment[hook_id]`, `ecs:stop_deployment[service_deployment_arn]` capistrano tasks for operating ECS-managed blue/green deployments (lifecycle hook approval / rollback / abort).
8
+ - Add `ecs:latest_deployment` capistrano task that prints the in-progress service deployment, or the most recent one if none is in progress, as JSON (status, revisions, circuit breaker state, rollback details, lifecycle hooks). With `FAIL_ON_ERROR=1`, the task fails when the deployment ended in `ROLLBACK_SUCCESSFUL`, `ROLLBACK_FAILED` or `STOPPED`.
8
9
 
9
10
  ### Breaking change
10
11
 
@@ -12,6 +13,8 @@
12
13
 
13
14
  ### Enhancement
14
15
 
16
+ - `EcsDeploy::Service.wait_all_running` (used by `ecs:deploy`) now raises `EcsDeploy::Service::DeploymentFailedError` when the deployment circuit breaker fails a deployment (rolled back or not), and `EcsDeploy::Service::RollbackFailedError` when the rollback also fails, instead of finishing successfully after the rollback. `wait_strategy: :service_deployment` now keeps waiting while a rollback is in progress.
17
+ - `wait_strategy: :legacy` now waits for the started deployment to reach `rolloutState: COMPLETED` when ECS returns it, instead of only comparing task counts (which could finish before tasks became healthy behind the load balancer). Services without `rolloutState` keep the previous check.
15
18
  - Add `wait_strategy` option to `EcsDeploy::Service` for ECS-managed blue/green deployments (`DeploymentController.Type=ECS` with `BLUE_GREEN`/`LINEAR`/`CANARY`). `wait_all_running` now auto-detects ECS-managed deployments and skips polling so Capistrano sessions do not block on multi-day Pause Hooks.
16
19
  - `EcsDeploy::Service#update_service` now forwards every field accepted by `Aws::ECS::Client#update_service` (aws-sdk-ecs 1.238+), including fields added after this gem release. Options that ECS cannot apply on an existing service (`launch_type`, `scheduling_strategy`, `role`, `client_token`, `deployment_controller`) are detected and logged as warnings when the user's value differs from the current service. `desired_count: 0` and `propagate_tags: "NONE"` are now honored (previously silently dropped by a truthiness check).
17
20
  - Bump minimum `aws-sdk-ecs` to `1.238` for `continue_service_deployment`, `stop_service_deployment`, `LINEAR`/`CANARY` strategy, `lifecycle_hooks`, and `LoadBalancer.advanced_configuration`.
data/README.md CHANGED
@@ -30,10 +30,13 @@ set :ecs_deploy_wait_timeout, 600 # default: 300
30
30
  set :ecs_wait_until_services_stable_max_attempts, 40 # optional
31
31
  set :ecs_wait_until_services_stable_delay, 15 # optional
32
32
  set :ecs_client_params, { retry_mode: "standard", max_attempts: 10 } # default: {}
33
+ set :ecs_docker_buildx_env, { "DOCKER_CONFIG" => "/path/to/docker/config" } # optional. Env vars for the `docker buildx` command used by use_digest. Merged with each task's docker_buildx_env (the per-task one takes precedence). default: {}
33
34
 
34
35
  set :ecs_tasks, [
35
36
  {
36
37
  name: "myapp-#{fetch(:rails_env)}",
38
+ use_digest: true, # optional. When true, each container_definitions[].image is rewritten to a digest reference (registry/repo@sha256:...) resolved via `docker buildx imagetools inspect` at registration time. Requires the `docker` CLI with buildx on the deploy host; resolution failure aborts the deploy.
39
+ docker_buildx_env: { "DOCKER_CONFIG" => "/path/to/docker/config" }, # optional. Env vars for the `docker buildx` command. Merged on top of :ecs_docker_buildx_env.
37
40
  container_definitions: [
38
41
  {
39
42
  name: "myapp",
@@ -239,15 +242,44 @@ set :ecs_services, [
239
242
  |--------|--------|---------|
240
243
  | `wait_strategy:` | `nil` (auto), `:legacy`, `:none`, `:service_deployment` | `nil` auto-detects ECS-managed deployments and skips waiting (multi-day Pause Hooks make blocking impractical). `:legacy` matches pre-1.1 behavior. `:service_deployment` polls `list_service_deployments` (not recommended for sessions). |
241
244
 
245
+ When `ecs:deploy` waits for a service (`:legacy` or `:service_deployment`) and the deployment circuit breaker fails the deployment, the task raises `EcsDeploy::Service::DeploymentFailedError` (whether ECS rolled back or left the failed deployment in place). If the rollback itself fails, it raises `EcsDeploy::Service::RollbackFailedError`, a subclass of `DeploymentFailedError`. Either way `cap` exits with a non-zero status.
246
+
247
+ For rolling update (`ECS`) services, `:legacy` waits until the deployment it started reaches `rolloutState: COMPLETED` (the steady state judged by ECS, e.g. load balancer health checks passed) and the old deployment is drained. For services without `rolloutState` (e.g. `CODE_DEPLOY`, Classic Load Balancer), it falls back to `deployments.size == 1 && runningCount == desiredCount`.
248
+
249
+ For ECS-managed blue/green deployments that `ecs:deploy` does not wait for, run `ecs:latest_deployment FAIL_ON_ERROR=1` afterwards (e.g. as a later CI step) to fail when the deployment was rolled back.
250
+
242
251
  ### Operational tasks
243
252
 
244
253
  ```sh
245
254
  bundle exec cap <stage> ecs:describe_deployment # list in-flight deployments with lifecycle hook details
255
+ bundle exec cap <stage> ecs:latest_deployment # print the in-progress deployment, or the most recent one if none, as JSON
256
+ bundle exec cap <stage> ecs:latest_deployment FAIL_ON_ERROR=1 # same, but exit non-zero if it ended in ROLLBACK_SUCCESSFUL, ROLLBACK_FAILED or STOPPED
246
257
  bundle exec cap <stage> ecs:continue_deployment[hook-id] # approve a paused lifecycle hook
247
258
  bundle exec cap <stage> ecs:rollback_deployment[hook-id] # reject a paused lifecycle hook (ECS rolls back)
248
259
  bundle exec cap <stage> ecs:stop_deployment[arn] # stop an in-progress deployment; STOP_TYPE=ABORT or ROLLBACK
249
260
  ```
250
261
 
262
+ `ecs:latest_deployment` prints a JSON array to stdout, one element per service and region. `service_deployment` is the `DescribeServiceDeployments` result with snake_case keys and ISO 8601 times (`null` if the service has no deployment). `failed` is true when it ended in `ROLLBACK_SUCCESSFUL`, `ROLLBACK_FAILED` or `STOPPED`.
263
+
264
+ ```json
265
+ [
266
+ {
267
+ "service": "myapp",
268
+ "cluster": "myapp-cluster",
269
+ "region": "ap-northeast-1",
270
+ "failed": true,
271
+ "service_deployment": {
272
+ "service_deployment_arn": "arn:aws:ecs:...",
273
+ "status": "ROLLBACK_SUCCESSFUL",
274
+ "deployment_circuit_breaker": { "status": "TRIGGERED", "failure_count": 3, "threshold": 3 },
275
+ "rollback": { "reason": "...", "started_at": "2026-12-01T10:00:00Z", "service_revision_arn": "arn:aws:ecs:..." }
276
+ }
277
+ }
278
+ ]
279
+ ```
280
+
281
+ For example: `bundle exec cap <stage> ecs:latest_deployment | jq -r '.[] | "\(.service) \(.service_deployment.status)"'`
282
+
251
283
  ### Caveats
252
284
 
253
285
  - `deployment_controller` is immutable on an existing service. To switch an existing `CODE_DEPLOY` service to `ECS`, delete and re-create the service.
@@ -1,5 +1,6 @@
1
1
  require 'ecs_deploy'
2
2
  require 'ecs_deploy/instance_fluctuation_manager'
3
+ require "json"
3
4
 
4
5
  namespace :ecs do
5
6
  task :configure do
@@ -11,6 +12,7 @@ namespace :ecs do
11
12
  c.ecs_wait_until_services_stable_max_attempts = fetch(:ecs_wait_until_services_stable_max_attempts) if fetch(:ecs_wait_until_services_stable_max_attempts)
12
13
  c.ecs_wait_until_services_stable_delay = fetch(:ecs_wait_until_services_stable_delay) if fetch(:ecs_wait_until_services_stable_delay)
13
14
  c.ecs_client_params = fetch(:ecs_client_params) if fetch(:ecs_client_params)
15
+ c.docker_buildx_env = fetch(:ecs_docker_buildx_env) if fetch(:ecs_docker_buildx_env)
14
16
  end
15
17
 
16
18
  if ENV["TARGET_CLUSTER"]
@@ -32,6 +34,8 @@ namespace :ecs do
32
34
  task_definition = EcsDeploy::TaskDefinition.new(
33
35
  region: region,
34
36
  task_definition_name: t[:name],
37
+ use_digest: t[:use_digest],
38
+ docker_buildx_env: t[:docker_buildx_env],
35
39
  container_definitions: t[:container_definitions],
36
40
  task_role_arn: t[:task_role_arn],
37
41
  execution_role_arn: t[:execution_role_arn],
@@ -123,6 +127,23 @@ namespace :ecs do
123
127
  end
124
128
  end
125
129
 
130
+ desc "Print the in-progress (or, if none, the most recent) ECS service deployment of each service in :ecs_services as JSON (FAIL_ON_ERROR=1: fail if it was rolled back or stopped)"
131
+ task latest_deployment: [:configure] do
132
+ if fetch(:ecs_services)
133
+ regions = Array(fetch(:ecs_region))
134
+ regions = [EcsDeploy.config.default_region] if regions.empty?
135
+ results = EcsDeploy::ServiceDeployment.latest(
136
+ services: fetch(:ecs_services),
137
+ regions: regions,
138
+ default_cluster: fetch(:ecs_default_cluster),
139
+ )
140
+ $stdout.puts JSON.pretty_generate(results)
141
+ if %w[1 true yes].include?(ENV["FAIL_ON_ERROR"].to_s.downcase)
142
+ EcsDeploy::ServiceDeployment.raise_if_failed(results)
143
+ end
144
+ end
145
+ end
146
+
126
147
  desc "Continue an ECS service deployment paused at a lifecycle hook"
127
148
  task :continue_deployment, [:hook_id] => [:configure] do |_t, args|
128
149
  raise "hook_id is required: cap ... ecs:continue_deployment[hook_id]" unless args[:hook_id]
@@ -9,7 +9,8 @@ module EcsDeploy
9
9
  :ecs_service_role,
10
10
  :ecs_wait_until_services_stable_max_attempts,
11
11
  :ecs_wait_until_services_stable_delay,
12
- :ecs_client_params
12
+ :ecs_client_params,
13
+ :docker_buildx_env
13
14
 
14
15
  def initialize
15
16
  @log_level = :info
@@ -18,6 +19,7 @@ module EcsDeploy
18
19
  @ecs_wait_until_services_stable_max_attempts = 40
19
20
  @ecs_wait_until_services_stable_delay = 15
20
21
  @ecs_client_params = {}
22
+ @docker_buildx_env = {}
21
23
  end
22
24
  end
23
25
  end
@@ -6,6 +6,15 @@ module EcsDeploy
6
6
  MAX_DESCRIBE_SERVICES = 10
7
7
 
8
8
  class TooManyAttemptsError < StandardError; end
9
+ # The deployment failed (e.g. the deployment circuit breaker tripped) and
10
+ # was rolled back, or was left failed because rollback is disabled.
11
+ class DeploymentFailedError < StandardError; end
12
+ # The deployment failed and the rollback that followed failed as well.
13
+ class RollbackFailedError < DeploymentFailedError; end
14
+
15
+ # Statuses of a service deployment (ListServiceDeployments) that mean ECS
16
+ # is still working on it, including rollbacks started by the circuit breaker.
17
+ SERVICE_DEPLOYMENT_IN_FLIGHT_STATUSES = %w[PENDING IN_PROGRESS STOP_REQUESTED ROLLBACK_REQUESTED ROLLBACK_IN_PROGRESS].freeze
9
18
 
10
19
  attr_reader :cluster, :region, :service_name, :delete, :deploy_started_at, :wait_strategy
11
20
 
@@ -201,6 +210,12 @@ module EcsDeploy
201
210
  end
202
211
  end
203
212
 
213
+ # ID of the PRIMARY deployment that create_service / update_service started.
214
+ # Used to tell whether that deployment completed or was replaced by a rollback.
215
+ def deployment_id
216
+ Array(@response&.service&.deployments).find { |d| d.status == "PRIMARY" }&.id
217
+ end
218
+
204
219
  def skip_wait?
205
220
  case @wait_strategy
206
221
  when :none
@@ -238,26 +253,86 @@ module EcsDeploy
238
253
 
239
254
  legacy_threads(client, cl, ss, legacy_targets) + service_deployment_threads(client, cl, sd_targets)
240
255
  end
241
- threads.each(&:join)
256
+ # Join every thread before raising so that a failure in one service does
257
+ # not hide the outcome of the others.
258
+ errors = threads.filter_map do |t|
259
+ t.join
260
+ nil
261
+ rescue StandardError => e
262
+ e
263
+ end
264
+ raise errors.find { |e| e.is_a?(DeploymentFailedError) } || errors.first unless errors.empty?
265
+ end
266
+
267
+ # Returns nil while the deployment is still going, or [:ok] / [error_class, message]
268
+ # once it settled.
269
+ # rollout_state is the steady-state judgement made by ECS itself, so it is
270
+ # preferred. It is returned only for the rolling update (ECS) deployment
271
+ # type not behind a Classic Load Balancer; otherwise fall back to counting
272
+ # deployments and tasks like the services_stable waiter.
273
+ def self.legacy_deployment_result(service, s)
274
+ primary = s.deployments.find { |d| d.status == "PRIMARY" }
275
+ ours_id = service&.deployment_id
276
+ ours = ours_id && s.deployments.find { |d| d.id == ours_id }
277
+ # cf. https://github.com/aws/aws-sdk-ruby/blob/master/gems/aws-sdk-ecs/lib/aws-sdk-ecs/waiters.rb#L91-L96
278
+ stable = s.deployments.size == 1 && s.running_count == s.desired_count
279
+
280
+ if ours_id && primary && primary.id != ours_id
281
+ # Another deployment took over the one we started: a circuit breaker rollback.
282
+ rolled_back = [DeploymentFailedError, "deployment of service [#{s.service_name}] failed and was rolled back to #{primary.task_definition}"]
283
+ case primary.rollout_state
284
+ when "FAILED"
285
+ return [RollbackFailedError, "rollback of service [#{s.service_name}] failed: #{primary.rollout_state_reason}"]
286
+ when "COMPLETED"
287
+ return rolled_back
288
+ when nil
289
+ return stable ? rolled_back : nil
290
+ else
291
+ return nil
292
+ end
293
+ end
294
+
295
+ if ours&.rollout_state
296
+ case ours.rollout_state
297
+ when "FAILED"
298
+ # Circuit breaker tripped without rollback.
299
+ return [DeploymentFailedError, "deployment of service [#{s.service_name}] failed: #{ours.rollout_state_reason}"]
300
+ when "COMPLETED"
301
+ # Also wait for the old deployment to drain, as before.
302
+ return s.deployments.size == 1 ? [:ok] : nil
303
+ else
304
+ return nil
305
+ end
306
+ end
307
+
308
+ stable ? [:ok] : nil
242
309
  end
243
310
 
244
311
  def self.legacy_threads(client, cluster, all_services, targets)
245
312
  targets.map(&:service_name).each_slice(MAX_DESCRIBE_SERVICES).map do |chunked_service_names|
246
313
  Thread.new do
314
+ Thread.current.report_on_exception = false # wait_all_running re-raises it
315
+ failures = []
247
316
  EcsDeploy.config.ecs_wait_until_services_stable_max_attempts.times do
248
317
  EcsDeploy.logger.info "waiting for services to stabilize [#{chunked_service_names.join(", ")}] [#{cluster}]"
249
318
  resp = client.describe_services(cluster: cluster, services: chunked_service_names)
250
319
  resp.services.each do |s|
251
- # cf. https://github.com/aws/aws-sdk-ruby/blob/master/gems/aws-sdk-ecs/lib/aws-sdk-ecs/waiters.rb#L91-L96
252
- if s.deployments.size == 1 && s.running_count == s.desired_count
253
- chunked_service_names.delete(s.service_name)
254
- end
255
320
  service = all_services.detect { |sc| sc.service_name == s.service_name }
256
321
  service&.log_events(s)
322
+ result = legacy_deployment_result(service, s)
323
+ next unless result
324
+ chunked_service_names.delete(s.service_name)
325
+ next if result == [:ok]
326
+ EcsDeploy.logger.error "#{result[1]} [#{cluster}]"
327
+ failures << result
257
328
  end
258
329
  break if chunked_service_names.empty?
259
330
  sleep EcsDeploy.config.ecs_wait_until_services_stable_delay
260
331
  end
332
+ unless failures.empty?
333
+ klass = failures.any? { |f| f[0] == RollbackFailedError } ? RollbackFailedError : DeploymentFailedError
334
+ raise klass, failures.map { |f| f[1] }.join("; ")
335
+ end
261
336
  raise TooManyAttemptsError unless chunked_service_names.empty?
262
337
  end
263
338
  end
@@ -266,14 +341,19 @@ module EcsDeploy
266
341
  def self.service_deployment_threads(client, cluster, targets)
267
342
  targets.map do |service|
268
343
  Thread.new do
344
+ Thread.current.report_on_exception = false # wait_all_running re-raises it
269
345
  pending = true
346
+ # Service deployments observed in flight since this deploy; their final
347
+ # status decides whether the command succeeds.
348
+ seen_arns = []
270
349
  EcsDeploy.config.ecs_wait_until_services_stable_max_attempts.times do
271
350
  EcsDeploy.logger.info "waiting for service deployment to settle [#{service.service_name}] [#{cluster}]"
272
351
  arns = client.list_service_deployments(
273
352
  cluster: cluster,
274
353
  service: service.service_name,
275
- status: %w[IN_PROGRESS PENDING],
354
+ status: SERVICE_DEPLOYMENT_IN_FLIGHT_STATUSES,
276
355
  ).service_deployments.map(&:service_deployment_arn)
356
+ seen_arns |= arns
277
357
  if arns.empty?
278
358
  pending = false
279
359
  break
@@ -281,10 +361,27 @@ module EcsDeploy
281
361
  sleep EcsDeploy.config.ecs_wait_until_services_stable_delay
282
362
  end
283
363
  raise TooManyAttemptsError if pending
364
+ check_service_deployments_result(client, cluster, service, seen_arns)
284
365
  end
285
366
  end
286
367
  end
287
368
 
369
+ def self.check_service_deployments_result(client, cluster, service, arns)
370
+ return if arns.empty?
371
+ deployments = arns.each_slice(20).flat_map do |chunk|
372
+ client.describe_service_deployments(service_deployment_arns: chunk).service_deployments
373
+ end
374
+ failed = deployments.reject { |d| d.status == "SUCCESSFUL" }
375
+ return if failed.empty?
376
+
377
+ messages = failed.map do |d|
378
+ "service deployment of [#{service.service_name}] ended with status=#{d.status}#{d.status_reason ? " reason=#{d.status_reason}" : ""} (#{d.service_deployment_arn})"
379
+ end
380
+ messages.each { |m| EcsDeploy.logger.error "#{m} [#{cluster}]" }
381
+ klass = failed.any? { |d| d.status == "ROLLBACK_FAILED" } ? RollbackFailedError : DeploymentFailedError
382
+ raise klass, messages.join("; ")
383
+ end
384
+
288
385
  private
289
386
 
290
387
  def task_definition_name_with_revision
@@ -1,7 +1,10 @@
1
+ require "time"
2
+
1
3
  module EcsDeploy
2
4
  module ServiceDeployment
3
5
  IN_FLIGHT_STATUSES = %w[IN_PROGRESS PENDING].freeze
4
6
  DESCRIBE_STATUSES = %w[IN_PROGRESS PENDING STOPPED].freeze
7
+ FAILED_STATUSES = %w[ROLLBACK_SUCCESSFUL ROLLBACK_FAILED STOPPED].freeze
5
8
 
6
9
  class HookNotFoundError < StandardError; end
7
10
 
@@ -15,6 +18,72 @@ module EcsDeploy
15
18
  end
16
19
  end
17
20
 
21
+ # Returns, for each service and region, the in-flight service deployment,
22
+ # or the most recent one when nothing is in flight, as a JSON-ready Hash:
23
+ # { service:, cluster:, region:, failed:, service_deployment: {...} or nil }
24
+ # `failed` is true when the deployment ended in one of FAILED_STATUSES;
25
+ # in-flight deployments are never failed.
26
+ def latest(services:, regions:, default_cluster:)
27
+ results = []
28
+ each_target(services: services, regions: regions, default_cluster: default_cluster) do |client, cluster, svc, region|
29
+ d = latest_deployment(client, cluster, svc[:name])
30
+ results << {
31
+ service: svc[:name],
32
+ cluster: cluster,
33
+ region: region,
34
+ failed: d ? FAILED_STATUSES.include?(d.status) : false,
35
+ service_deployment: d && json_ready(d.to_h),
36
+ }
37
+ end
38
+ results
39
+ end
40
+
41
+ # Raises DeploymentFailedError (RollbackFailedError if any rollback failed)
42
+ # when a result of .latest is failed.
43
+ def raise_if_failed(results)
44
+ failed = results.select { |r| r[:failed] }
45
+ return if failed.empty?
46
+
47
+ messages = failed.map do |r|
48
+ d = r[:service_deployment]
49
+ "[#{r[:service]}] [#{r[:cluster]}] [#{r[:region]}] status=#{d[:status]} (#{d[:service_deployment_arn]})"
50
+ end
51
+ rollback_failed = failed.any? { |r| r[:service_deployment][:status] == "ROLLBACK_FAILED" }
52
+ klass = rollback_failed ? EcsDeploy::Service::RollbackFailedError : EcsDeploy::Service::DeploymentFailedError
53
+ raise klass, "latest service deployment failed: #{messages.join("; ")}"
54
+ end
55
+
56
+ def latest_deployment(client, cluster, service_name)
57
+ briefs = list_all_briefs(client, cluster, service_name, statuses: EcsDeploy::Service::SERVICE_DEPLOYMENT_IN_FLIGHT_STATUSES)
58
+ briefs = list_all_briefs(client, cluster, service_name) if briefs.empty?
59
+ latest = briefs.max_by { |b| b.created_at || Time.at(0) }
60
+ return nil unless latest
61
+ client.describe_service_deployments(service_deployment_arns: [latest.service_deployment_arn]).service_deployments.first
62
+ end
63
+
64
+ def list_all_briefs(client, cluster, service_name, statuses: nil)
65
+ params = { cluster: cluster, service: service_name, max_results: 100 }
66
+ params[:status] = statuses if statuses
67
+ briefs = []
68
+ loop do
69
+ resp = client.list_service_deployments(params)
70
+ briefs.concat(resp.service_deployments)
71
+ break unless resp.next_token
72
+ params[:next_token] = resp.next_token
73
+ end
74
+ briefs
75
+ end
76
+
77
+ # Converts Time values (which JSON would render with Time#to_s) to ISO 8601.
78
+ def json_ready(value)
79
+ case value
80
+ when Hash then value.transform_values { |v| json_ready(v) }
81
+ when Array then value.map { |v| json_ready(v) }
82
+ when Time then value.utc.iso8601
83
+ else value
84
+ end
85
+ end
86
+
18
87
  def invoke_lifecycle_hook(hook_id:, action:, services:, regions:, default_cluster:)
19
88
  found = false
20
89
  each_target(services: services, regions: regions, default_cluster: default_cluster) do |client, cluster, svc|
@@ -46,7 +115,7 @@ module EcsDeploy
46
115
  cluster = svc[:cluster] || default_cluster
47
116
  regions.each do |r|
48
117
  client = Aws::ECS::Client.new(EcsDeploy.config.ecs_client_params.merge(region: r))
49
- yield client, cluster, svc
118
+ yield client, cluster, svc, r
50
119
  end
51
120
  end
52
121
  end
@@ -1,5 +1,18 @@
1
+ require "open3"
2
+
1
3
  module EcsDeploy
2
4
  class TaskDefinition
5
+ DIGEST_SUFFIX = /@sha256:[0-9a-f]{64}\z/
6
+ DIGEST_FORMAT = /\Asha256:[0-9a-f]{64}\z/
7
+
8
+ # Process-wide cache of resolved digests keyed by image reference,
9
+ # so the same image is only inspected via docker once per process.
10
+ @digest_cache = {}
11
+
12
+ class << self
13
+ attr_reader :digest_cache
14
+ end
15
+
3
16
  def self.deregister(arn, region: nil)
4
17
  region ||= EcsDeploy.config.default_region
5
18
  params ||= EcsDeploy.config.ecs_client_params
@@ -10,8 +23,12 @@ module EcsDeploy
10
23
  EcsDeploy.logger.info "deregistered task definition [#{arn}] [#{client.config.region}] [#{Paint['OK', :green]}]"
11
24
  end
12
25
 
13
- def initialize(task_definition_name:, region: nil, **options)
26
+ def initialize(task_definition_name:, region: nil, use_digest: false, docker_buildx_env: nil, **options)
14
27
  @task_definition_name = task_definition_name
28
+ @use_digest = use_digest
29
+ @docker_buildx_env = (EcsDeploy.config.docker_buildx_env || {})
30
+ .merge(docker_buildx_env || {})
31
+ .map { |k, v| [k.to_s, v&.to_s] }.to_h
15
32
  region ||= EcsDeploy.config.default_region
16
33
  params ||= EcsDeploy.config.ecs_client_params
17
34
 
@@ -49,11 +66,61 @@ module EcsDeploy
49
66
  end
50
67
 
51
68
  def register
52
- res = @client.register_task_definition(
53
- @options.merge(family: @task_definition_name)
54
- )
69
+ options = @options.merge(family: @task_definition_name)
70
+ options[:container_definitions] = apply_digests(options[:container_definitions]) if @use_digest
71
+ res = @client.register_task_definition(options)
55
72
  EcsDeploy.logger.info "registered task definition [#{@task_definition_name}] [#{@region}] [#{Paint['OK', :green]}]"
56
73
  res.task_definition
57
74
  end
75
+
76
+ private
77
+
78
+ def apply_digests(container_definitions)
79
+ (container_definitions || []).map do |cd|
80
+ image = cd[:image]
81
+ next cd if image.nil? || image.empty?
82
+
83
+ resolved = resolve_image_with_digest(image)
84
+ EcsDeploy.logger.info "resolved image [#{image}] -> [#{resolved}]" if resolved != image
85
+ cd.merge(image: resolved)
86
+ end
87
+ end
88
+
89
+ def resolve_image_with_digest(image)
90
+ return image if image =~ DIGEST_SUFFIX
91
+
92
+ "#{repository_without_tag(image)}@#{fetch_manifest_digest(image)}"
93
+ end
94
+
95
+ # "registry:5000/ns/repo:tag" -> "registry:5000/ns/repo"
96
+ # "registry:5000/ns/repo" -> "registry:5000/ns/repo"
97
+ # "repo:tag" -> "repo"
98
+ def repository_without_tag(image)
99
+ name_start = (idx = image.rindex("/")) ? idx + 1 : 0
100
+ colon = image.index(":", name_start)
101
+ colon ? image[0...colon] : image
102
+ end
103
+
104
+ def fetch_manifest_digest(image)
105
+ cache = self.class.digest_cache
106
+ if (cached = cache[image])
107
+ EcsDeploy.logger.debug "using cached digest for #{image}: #{cached}"
108
+ return cached
109
+ end
110
+
111
+ EcsDeploy.logger.debug "docker buildx imagetools inspect --format '{{.Manifest.Digest}}' #{image}"
112
+ stdout, stderr, status =
113
+ Open3.capture3(@docker_buildx_env, "docker", "buildx", "imagetools", "inspect", "--format", "{{.Manifest.Digest}}", image)
114
+ unless status.success?
115
+ raise EcsDeploy::Error, "docker buildx imagetools inspect failed for '#{image}': #{stderr.strip}"
116
+ end
117
+ digest = stdout.strip
118
+ unless digest =~ DIGEST_FORMAT
119
+ raise EcsDeploy::Error, "Unexpected digest for '#{image}': #{digest.inspect}"
120
+ end
121
+ cache[image] = digest
122
+ rescue Errno::ENOENT => e
123
+ raise EcsDeploy::Error, "docker command not found: #{e.message}"
124
+ end
58
125
  end
59
126
  end
@@ -1,3 +1,3 @@
1
1
  module EcsDeploy
2
- VERSION = "2.0.0"
2
+ VERSION = "2.2.0"
3
3
  end
data/lib/ecs_deploy.rb CHANGED
@@ -7,6 +7,8 @@ require 'terminal-table'
7
7
  require 'paint'
8
8
 
9
9
  module EcsDeploy
10
+ class Error < StandardError; end
11
+
10
12
  def self.logger
11
13
  @logger ||= Logger.new(STDOUT).tap do |l|
12
14
  l.level = Logger.const_get(config.log_level.to_s.upcase)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ecs_deploy
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0
4
+ version: 2.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - joker1007
@@ -239,7 +239,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
239
239
  - !ruby/object:Gem::Version
240
240
  version: '0'
241
241
  requirements: []
242
- rubygems_version: 4.0.6
242
+ rubygems_version: 4.0.20
243
243
  specification_version: 4
244
244
  summary: AWS ECS deploy helper
245
245
  test_files: []