はじめまして。新卒入社2年目の大林です。 本記事ではCodeCommitリポジトリのブランチごとにgit pullのアクセス制御をしようとして失敗した話を紹介します。
やろうとしたこと
- ローカル環境からIAMユーザーにログインする。
- 環境操作権限があるIAMロールにスイッチして、環境サービス内のEC2インスタンスに接続する。
- 本番環境サービス内のEC2インスタンスは本番環境サービス内のEC2インスタンス用IAMロールに、開発環境サービス内のEC2インスタンスは開発環境サービス内のEC2インスタンス用IAMロールにスイッチする。
- CodeCommitリポジトリへのgit pullを行う。

本番環境サービス内のEC2インスタンス用IAMロールに付与した権限
masterブランチへのgit pullを許可、developブランチへのgit pullを拒否
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"codecommit:GitPull"
],
"Resource": "arn:aws:codecommit:ap-northeast-1:XXXXXXXXXXXX:*",
"Condition": {
"StringEqualsIfExists": {
"codecommit:References": [
"refs/heads/master"
]
}
}
},
{
"Sid": "VisualEditor1",
"Effect": "Deny",
"Action": [
"codecommit:GitPull"
],
"Resource": "arn:aws:codecommit:ap-northeast-1:XXXXXXXXXXXX:*",
"Condition": {
"StringEqualsIfExists": {
"codecommit:References": [
"refs/heads/develop"
]
}
}
}
]
}
開発環境サービス内のEC2インスタンス用IAMロールに付与した権限
developブランチからのgit pullを許可、masterブランチへのgit pullを拒否
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Deny",
"Action": [
"codecommit:GitPull"
],
"Resource": "arn:aws:codecommit:ap-northeast-1:XXXXXXXXXXXX:*",
"Condition": {
"StringEqualsIfExists": {
"codecommit:References": [
"refs/heads/master"
]
}
}
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"codecommit:GitPull"
],
"Resource": "arn:aws:codecommit:ap-northeast-1:XXXXXXXXXXXX:*",
"Condition": {
"StringEqualsIfExists": {
"codecommit:References": [
"refs/heads/develop"
]
}
}
}
]
}
テスト実施/結果
テスト
本番環境サービス内のEC2インスタンスから本番環境サービス内のEC2インスタンス用のIAMロールにスイッチして、git cloneを実行する。
期待動作
masterブランチからはcloneできるが、developブランチからはcloneできない。
結果
どちらのブランチからもcloneできなかった。
$ git clone -b master https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/y-obayashi-test Cloning into 'y-obayashi-test'... fatal: unable to access 'https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/y-obayashi-test/': The requested URL returned error: 403 $ git clone -b develop https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/y-obayashi-test Cloning into 'y-obayashi-test'... fatal: unable to access 'https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/y-obayashi-test/': The requested URL returned error: 403
開発環境サービス内のEC2インスタンスからもgit cloneを実行しましたが、ブランチごとの制御はうまくいきませんでした。
結論
サポートに問い合わせたところ、「アクション GitPull が条件キー codecommit:References に対応していないため、特定のブランチに対する制御ができない」との回答をいただきました。 そのため、CodeCommitリポジトリにアクセスできるIAMロールを作成して、CodeCommitリポジトリにアクセスするときはその都度IAMロールをスイッチして作業をすることにしました。 上記のIAMロールには、どのブランチでもgit pullを実行できる権限を付与しました。

さいごに
今回は、CodeCommitリポジトリのブランチごとにgit pullのアクセス制御をしようとして失敗した話を紹介しました。
AWSの学習は知識として覚えるだけではなく、実際に手を動かしてみることが大事だと思いました。