github.com/GoogleContainerTools/kaniko@v1.23.0/pkg/buildcontext/s3.go (about) 1 /* 2 Copyright 2018 Google LLC 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package buildcontext 18 19 import ( 20 "context" 21 "fmt" 22 "os" 23 "path/filepath" 24 "strings" 25 26 kConfig "github.com/GoogleContainerTools/kaniko/pkg/config" 27 "github.com/GoogleContainerTools/kaniko/pkg/constants" 28 "github.com/GoogleContainerTools/kaniko/pkg/util" 29 "github.com/GoogleContainerTools/kaniko/pkg/util/bucket" 30 "github.com/aws/aws-sdk-go-v2/aws" 31 "github.com/aws/aws-sdk-go-v2/config" 32 s3manager "github.com/aws/aws-sdk-go-v2/feature/s3/manager" 33 "github.com/aws/aws-sdk-go-v2/service/s3" 34 ) 35 36 // S3 unifies calls to download and unpack the build context. 37 type S3 struct { 38 context string 39 } 40 41 // UnpackTarFromBuildContext download and untar a file from s3 42 func (s *S3) UnpackTarFromBuildContext() (string, error) { 43 bucket, item, err := bucket.GetNameAndFilepathFromURI(s.context) 44 if err != nil { 45 return "", fmt.Errorf("getting bucketname and filepath from context: %w", err) 46 } 47 48 endpoint := os.Getenv(constants.S3EndpointEnv) 49 forcePath := false 50 if strings.ToLower(os.Getenv(constants.S3ForcePathStyle)) == "true" { 51 forcePath = true 52 } 53 54 customResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { 55 if endpoint != "" { 56 return aws.Endpoint{ 57 URL: endpoint, 58 }, nil 59 } 60 return aws.Endpoint{}, &aws.EndpointNotFoundError{} 61 }) 62 63 cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithEndpointResolverWithOptions(customResolver)) 64 if err != nil { 65 return bucket, err 66 } 67 client := s3.NewFromConfig(cfg, func(options *s3.Options) { 68 if endpoint != "" { 69 options.UsePathStyle = forcePath 70 } 71 }) 72 downloader := s3manager.NewDownloader(client) 73 directory := kConfig.BuildContextDir 74 tarPath := filepath.Join(directory, constants.ContextTar) 75 if err := os.MkdirAll(directory, 0750); err != nil { 76 return directory, err 77 } 78 file, err := os.Create(tarPath) 79 if err != nil { 80 return directory, err 81 } 82 _, err = downloader.Download(context.TODO(), file, 83 &s3.GetObjectInput{ 84 Bucket: aws.String(bucket), 85 Key: aws.String(item), 86 }) 87 if err != nil { 88 return directory, err 89 } 90 91 return directory, util.UnpackCompressedTar(tarPath, directory) 92 }