LoginSignup
2
0

More than 5 years have passed since last update.

CodeBuild内のgradleからでIAM Roleを使ってS3にアクセスする

Last updated at Posted at 2018-10-22

CodeBuildでJavaのコードをビルドする際、S3をmavenリポジトリとして使用することにしました。

その際設定でけっこう詰まったので記事にしてみました。

credentialsで設定する

gradleのドキュメントには次のように書かれています。

build.gradle
repositories {
    maven {
        url "s3://myCompanyBucket/maven2"
        credentials(AwsCredentials) {
            accessKey "someKey"
            secretKey "someSecret"
            // optional
            sessionToken "someSTSToken"
        }
    }
}

今回はCodeBuildにassumeされたIAM RoleからaccessKey, secretKey, sessionTokenを取得するので、次のようなコードになります。

build.gradle
import com.amazonaws.auth.AWSCredentialsProviderChain
import com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper
import com.amazonaws.auth.AWSSessionCredentials

...

repositories {
    maven {
        url "s3://sample-maven-repository/repository"
        credentials(AwsCredentials) {
            def credentials = new AWSCredentialsProviderChain(
                new EC2ContainerCredentialsProviderWrapper()
            ).getCredentials()
            accessKey credentials.getAWSAccessKeyId()
            secretKey credentials.getAWSSecretKey()
            if (credentials instanceof AWSSessionCredentials) { 
                sessionToken credentials.sessionToken
            }
        }
    }
}

authenticationで指定するとエラーになる

一方、gradleのドキュメントには下記のような指定方法も記載してあります。

build.gradle
repositories {
    maven {
        url "s3://myCompanyBucket/maven2"
        authentication {
           awsIm(AwsImAuthentication) // load from EC2 role or env var
        }
    }
}

しかし、上記だとビルドはエラーとなります。
エラーログを見た所、InstanceProfileCredentialsProviderhttp://169.254.169.254/latest/meta-data/iam/security-credentials/にアクセスしており、そこでエラーが発生し、全体の処理が終了しているようです。

2
0
1

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
2
0