0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS EmulatorをGitHub Actionsで使ってみた

0
Posted at

GitHub Actionsなどでモックを使用してAWSへの連携部分をテストしていることがあると思うのですが、実際のAWSリソースとは挙動が若干違うなど結局デプロイするまでわからないみたいなことになりがちです。
こういったときに実際のAWSアカウントでお金をかけずにテストができたらなと思うことが多々あるところに、AWS Emulatorが出たので試してみました。

AWS Emulatorとは

実際のAWS環境にリソースを作成することなく、AWSのAPIをローカルで試すことができるツールです。
利用料金もとくに発生しないのでお財布にも優しいツールになっています。
https://docs.aws.amazon.com/emulator/latest/userguide/what-is-service.html

やること

まずはローカルPCでAWS Emulatorを使ってまずはTerraformからAmazon SQSを作成してみます。
動くことが確認出来たらGitHub Actionsを使ってmainブランチへのPR作成時にSQSを作成できるようなワークフローを試してみます。

ローカルで試してみる

環境作成

私の環境はWindows11でWSL2を利用してます。
Dockerコンテナ上でAWS Emulatorを動かせるようなのでドキュメントに記載されているDockerfileを使ってみます。
https://docs.aws.amazon.com/emulator/latest/userguide/getting-started-docker.html

FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal
ADD https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator-x86_64.rpm /tmp/aws-emulator.rpm
RUN rpm -i /tmp/aws-emulator.rpm && rm /tmp/aws-emulator.rpm \
    && mkdir -p /home/emulator && chown 1000 /home/emulator
USER 1000
ENV HOME=/home/emulator
EXPOSE 9297
ENTRYPOINT ["aws-emulator", "-b", "0.0.0.0"]

Dockerfileを作成したら以下のコマンドでビルドします。

docker build -t aws-emulator .

ビルドが完了したらコンテナがローカルマシンと共有するディレクトリを作成します。

mkdir -p ~/.aws/emulator

以下のコマンドでコンテナを起動します。

PORT=9297
docker run --rm --memory=2g --memory-swap=2g -p 127.0.0.1:$PORT:$PORT \
  -e HOME="$HOME" -v "$HOME/.aws/emulator:$HOME/.aws/emulator" \
  aws-emulator -p $PORT

コンテナが起動したら別のターミナルで以下のコマンドを実行してSDKなどの向き先をAWS Emulatorに変更します。

export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE="$HOME/.aws/emulator/9297/emulator_credentials"
export AWS_CONFIG_FILE="$HOME/.aws/emulator/9297/config"
export AWS_CA_BUNDLE="$HOME/.aws/emulator/9297/ca.pem"
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1

AWS Emulatorに向き先が変わっているかはget-caller-identityコマンドを実行して確認します。
以下のようにAccountが000000000000でArnがarn:aws:iam::000000000000:user/emulatorになっていれば向き先が変わっています。

aws sts get-caller-identity

{
    "UserId": "AIDAH5I7GEMO7ADXNFAZU",
    "Account": "000000000000",
    "Arn": "arn:aws:iam::000000000000:user/emulator"
}

向き先が変わっていることが確認出来たら以下のmain.tfでSQSキューを作成します。

main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_sqs_queue" "test" {
  name = "terraform-test-queue"

  visibility_timeout_seconds = 30
  message_retention_seconds  = 345600

  tags = {
    Environment = "local"
    ManagedBy   = "Terraform"
  }
}

output "queue_url" {
  value = aws_sqs_queue.test.url
}

main.tfを作成したらApplyします。

terraform init
terraform plan
terraform apply -auto-approve

Applyが完了すると以下のようにキューURLが確認できます。

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

queue_url = "https://sqs.us-east-1.amazonaws.com/000000000000/terraform-test-queue"

list-queuesコマンドでも作成されていることがわかります。

aws sqs list-queues
{
    "QueueUrls": [
        "https://sqs.us-east-1.amazonaws.com/000000000000/terraform-test-queue"
    ]
}

boto3でSQSにメッセージを送ってみる

環境作成が完了したら以下のPythonのboto3からSQSにメッセージを送ってみます。

send_message.py
import boto3

sqs = boto3.client("sqs")

queue_url = sqs.get_queue_url(
    QueueName="terraform-test-queue"
)["QueueUrl"]

response = sqs.send_message(
    QueueUrl=queue_url,
    MessageBody="test message dayo-",
)

print(response["MessageId"])

ファイルを作成したらPythonを実行してメッセージを送ります。

python send_message.py

受信もやってみます。

receive_message.py
import boto3

sqs = boto3.client("sqs")


queue_url = sqs.get_queue_url(
    QueueName="terraform-test-queue"
)["QueueUrl"]

response = sqs.receive_message(
    QueueUrl=queue_url,
    WaitTimeSeconds=10,
)

for message in response.get("Messages", []):
    print("MessageId:", message["MessageId"])
    print("Body:", message["Body"])

先ほど送ったメッセージが確認できます。

python receive_message.py

# レスポンス
MessageId: 9042bec9-eb25-4e85-a350-bae930e03cda
Body: test message dayo-

後か片付け

不要なコンテナが動いてるのは嫌なので削除しておきます。(必要なときに作り直せばよいですしね)

# Terraformでリソース作成するときは実際の本物のAWSリソースが消えてないか確認をお勧めします
terraform destroy

docker rmi aws-emulator:latest

GitHub Actionsから試してみる

ワークフローファイル作成

ここからは実際にGitHub Actionsで試してみます。
PythonのファイルとDockerfile、main.tfは同じものを使用します。
新規で作成するのはGitHub Actionsのワークフローファイルです。

作成したワークフローファイルは以下になります。

emulator-test.yml
name: AWS Emulator SQS Test

on:
  pull_request:
  workflow_dispatch:

permissions:
  contents: read

jobs:
  sqs-test:
    runs-on: ubuntu-latest

    steps:
      # 1. ソースコード取得
      - name: Checkout
        uses: actions/checkout@v4

      # 2. Pythonの準備
      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.14"

      # 3. boto3のインストール
      - name: Install boto3
        run: python -m pip install boto3

      # 4. Terraformの準備
      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3

      # 5. AWS EmulatorのDockerイメージ作成
      - name: Build AWS Emulator
        run: docker build -t aws-emulator .

      # 6. AWS Emulator起動
      - name: Start AWS Emulator
        run: |
          mkdir -p "$HOME/.aws/emulator"

          docker run -d --rm \
            --name aws-emulator \
            --user "$(id -u):$(id -g)" \
            --memory=2g \
            --memory-swap=2g \
            -p 127.0.0.1:9297:9297 \
            -e HOME="$HOME" \
            -e EMULATOR_TELEMETRY=off \
            -v "$HOME/.aws/emulator:$HOME/.aws/emulator" \
            aws-emulator

      # 7. AWS Emulatorの起動完了を待つ
      - name: Wait for AWS Emulator
        run: |
          for i in {1..60}; do
            if [ -f "$HOME/.aws/emulator/9297/ca.pem" ] &&
               curl -fsS \
                 --cacert "$HOME/.aws/emulator/9297/ca.pem" \
                 https://127.0.0.1:9297/__admin/health; then
              echo "AWS Emulator is ready"
              exit 0
            fi

            sleep 2
          done

          docker logs aws-emulator
          exit 1

      # 8. AWS Emulatorの接続情報設定
      - name: Configure AWS Emulator
        run: |
          {
            echo "AWS_ENDPOINT_URL=https://127.0.0.1:9297"
            echo "AWS_SHARED_CREDENTIALS_FILE=$HOME/.aws/emulator/9297/emulator_credentials"
            echo "AWS_CONFIG_FILE=$HOME/.aws/emulator/9297/config"
            echo "AWS_CA_BUNDLE=$HOME/.aws/emulator/9297/ca.pem"
            echo "AWS_EC2_METADATA_DISABLED=true"
            echo "AWS_DISABLE_HOST_PREFIX_INJECTION=true"
            echo "AWS_REGION=us-east-1"
            echo "AWS_DEFAULT_REGION=us-east-1"
          } >> "$GITHUB_ENV"

      # 9. 接続先がエミュレータであることを確認
      - name: Verify AWS Emulator
        run: |
          python - <<'PY'
          import boto3

          identity = boto3.client("sts").get_caller_identity()

          if identity["Account"] != "000000000000":
              raise RuntimeError("Not connected to AWS Emulator")

          print("Connected to AWS Emulator")
          PY

      # 10. Terraform初期化
      - name: Terraform Init
        run: terraform init -backend=false

      # 11. Terraform構文検証
      - name: Terraform Validate
        run: terraform validate

      # 12. TerraformでSQSキューを作成
      - name: Terraform Apply
        run: terraform apply -auto-approve

      # 13. boto3でSQSにメッセージ送信
      - name: Send SQS Message
        run: python send_message.py

      # 14. boto3でメッセージ受信・検証
      - name: Receive SQS Message
        run: python receive_message.py

      # 15. TerraformでSQSキューを削除
      - name: Terraform Destroy
        if: always()
        run: |
          if [ -f terraform.tfstate ]; then
            terraform destroy -auto-approve
          fi

      # 16. 失敗時はEmulatorのログを表示
      - name: Show Emulator Logs
        if: failure()
        run: docker logs aws-emulator || true

      # 17. Emulatorの停止
      - name: Stop AWS Emulator
        if: always()
        run: docker stop aws-emulator || true

「# 7. AWS Emulatorの起動完了を待つ」でエミュレータが完全に起動しているかチェックする処理を入れています。
起動できていればHTTPステータス200で返ってくるのでチェックに使ってます。
https://docs.aws.amazon.com/emulator/latest/userguide/point-sdk-to-emulator.html

(Optional) Check that the emulator is ready. The health check returns HTTP 200 with the body ok. It uses the same port as the API, over HTTPS.

最終的に以下のようなディレクトリ構成になります。

├── .github
│   └── workflows
│       └── emulator-test.yml
├── Dockerfile
├── main.tf
├── receive_message.py
└── send_message.py

ファイルを作成したら以下のコマンドでGitHubリポジトリに入れます。

# mainブランチにいることを確認
git branch

# mainブランチから作業ブランチを作成してpushまで実行
git checkout -b feature/test
git add .
git commit -m "ワークフローテスト"
git push origin feature/test

PRを作成して動作確認

ファイルの準備ができたらGitHub上でmainブランチ宛にPRを作成してみます。
ワークフローファイルで以下のようにしているのでPR作成時に動きだします。

on:
  pull_request:
  workflow_dispatch:

PRの画面では少しわかりにくいですが、うまくいっていれば以下の画像のようにワークフローファイルが動いていることがわかります。(最近UIが変わって少し見づらくなった)
image.png

Actionsタブから実行ログなどが確認できます。
terraform applyやPythonの実行が成功していることがわかります。
image.png

image.png

terraform destroyもエミュレータの方を削除してくれてます。
image.png

さいごに

今回はAWS EmulatorをGitHub Actionsで使ってみました。
使用自体も無料で簡単に使えるのでCIで積極的に導入するのはありだと思いました。
Terraformでリソース作成を試していますが、AWSサービスによってはそこまで再現されてないものもあるかもしれないのでそこだけは注意が必要そうです。
https://docs.aws.amazon.com/emulator/latest/userguide/fidelity.html

Fidelity for data plane APIs, and support for infrastructure as code tools such as AWS CloudFormation, Terraform, and the AWS CDK, varies by service. For what each label means, see docs/TAXONOMY.md in the aws-emulator-evaluation-suite repository.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?