kasei_sanのブログ

かせいさんのIT系のおぼえがきです。胡乱の方はnoteとtwitterへ

AWS CodeBuild の buildspec.yml のコマンドで curl の完了前に処理が終了する件とその対策

buildspec.yml(一部)

post_buildcurl を実行後にその戻り値をチェックする command を実行する

実際のコードでは、API Gatewayを叩いていた

version: 0.2

phases:
  post_build:
    commands:
      - curl https://example.com
      - echo $?

実行結果

すると、 curl が完了する前に、次のコマンドが実行され、最終的に curl が完了する前に post_build が完了してしまう

[Container] 2020/02/04 01:51:29 Running command curl https://example.com

[Container] 2020/02/04 01:51:29 Running command echo $?
0

[Container] 2020/02/04 01:51:29 Phase complete: POST_BUILD State: SUCCEEDED
[Container] 2020/02/04 01:51:29 Phase context status code:  Message: 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (6) Could not resolve host: example.com

原因

不明

対策

curlを使わないようにした

version: 0.2

phases:
  install:
    runtime-versions:
      ruby: 2.6

  post_build:
    commands:
      - ruby ./kick_api.rb
      - echo echo $?

kick_api.rb

require 'net/https'
require 'uri'

uri = URI.parse('https://example.com')
puts "Kick API: #{uri.to_s}"

res = Net::HTTP.get_response(uri)

puts "Responce code: #{res.code}"
puts "Responce body: #{res.body}"
res.value # 200以外なら例外を返す