Class: Kscript::KkAwsS3Utils

Inherits:
Base
  • Object
show all
Defined in:
lib/kscript/plugins/kk_aws_s3_utils.rb

Instance Attribute Summary

Attributes inherited from Base

#logger

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#human_output?, inherited, #with_error_handling

Constructor Details

#initialize(*args, **opts) ⇒ KkAwsS3Utils

初始化,支持所有参数通过 CLI 传递



19
20
21
22
23
24
25
26
27
28
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 19

def initialize(*args, **opts)
  super
  # 兼容 --file test.txt 以及 --file=test.txt
  @file = opts[:file] || args[0]
  @bucket = opts[:bucket] || args[1] || ENV.fetch('AWS_BUCKET', nil)
  @key = opts[:key] || args[2]
  @region = opts[:region] || ENV.fetch('AWS_REGION', nil)
  @access_key = opts[:access_key] || ENV.fetch('AWS_ACCESS_KEY_ID', nil)
  @secret_key = opts[:secret_key] || ENV.fetch('AWS_SECRET_ACCESS_KEY', nil)
end

Class Method Details

.argumentsObject

参数声明



53
54
55
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 53

def self.arguments
  '--file FILE --bucket BUCKET --key KEY --region REGION --access_key AK --secret_key SK'
end

.authorObject

作者



68
69
70
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 68

def self.author
  'kk'
end

.descriptionObject

描述



73
74
75
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 73

def self.description
  'Upload a file to AWS S3 for testing.'
end

.groupObject

分组



63
64
65
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 63

def self.group
  'cloud'
end

.usageObject

用法



58
59
60
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 58

def self.usage
  'kscript aws_s3 --file local.txt --bucket my-bucket --key test.txt --region ap-northeast-1 --access_key xxx --secret_key yyy'
end

Instance Method Details

#run(*_args, **_opts) ⇒ Object

主入口



31
32
33
34
35
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 31

def run(*_args, **_opts)
  with_error_handling do
    upload_file_to_s3
  end
end

#upload_file_to_s3Object

上传文件到 S3



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/kscript/plugins/kk_aws_s3_utils.rb', line 38

def upload_file_to_s3
  validate_params!
  logger.kinfo('Uploading file to S3...', file: @file, bucket: @bucket, key: @key, region: @region)
  s3 = Aws::S3::Resource.new(
    region: @region,
    access_key_id: @access_key,
    secret_access_key: @secret_key
  )
  obj = s3.bucket(@bucket).object(@key)
  obj.upload_file(@file)
  url = obj.public_url
  logger.kinfo('Upload success', url: url)
end