あきろぐ

いろいろめもするよ🐈🐈🐈

AmazonLinux2でyumが使えなくなったとき

Amazon Linux2を使ってEC2インスタンスを立てていたのですが、突然yumが使えなくなり戸惑ったのでその対処法について書きます。

エラー内容

遭遇したエラーは下記。
yum updateしようとすると、HTTPエラーが発生しアクセス許可されていないと言われてしまいました。

$ yum update -y
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Could not retrieve mirrorlist http://amazonlinux.ap-northeast-1.amazonaws.com/2/core/latest/x86_64/mirror.list error was
14: HTTP Error 403 - Forbidden


 One of the configured repositories failed (Unknown),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=<repoid> ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

yum-config-manager --disable <repoid>
        or
            subscription-manager repos --disable=<repoid>

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

Cannot find a valid baseurl for repo: amzn2-core/2/x86_64

原因

EC2インスタンスからS3にアクセスするためにインターネットを経由せず、VPCエンドポイントを使うように対象サブネットを紐づけしていたのですが、ポリシーを特定のバケットのみにしていたためyumレポジトリにアクセスできなくなっていたことが原因でした。
AmazonLinuxのyumレポジトリはS3上に置いてあるので、VPCエンドポイントのポリシーを特定のバケットのみに制限したことによってyumコマンドを実行してもS3上のレポジトリにアクセスすることができず、エラーとなりました。

デフォルトの設定だと、EC2インスタンスからS3のバケットへアクセスするには一旦インターネットを経由する必要がありました。しかし、VPCエンドポイントを作成し対象サブネットを紐づけすることによって、S3へのアクセスがインターネット経由ではなくVPCエンドポイント経由でできるようになります。そのため、yumでupdateしたりinstallしたりするときVPCエンドポイントを経由してS3にアクセスしようとするので、ポリシーの設定でyumレポジトリが配置されているバケットへのトラフィックを許可しておく必要があります。

対処法

ポリシーの編集は、[VPC]>[Endpoint]>[Policy]>[Edit]から行います。

# 公式ドキュメントより
{
  "Statement": [
    {
      "Sid": "Amazon Linux AMI Repository Access",
      "Principal": "*",
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:s3:::packages.*.amazonaws.com/*",
        "arn:aws:s3:::repo.*.amazonaws.com/*"
      ]
    }
  ]
}

上記のようにレポジトリへのトラフィックを許可すれば、yumコマンドが実行できるようになっていると思います。