public
Last active

Using Amazon IAM with Fog (example)

  • Download Gist
iam_fog.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
require 'fog'
 
username = 'testuser'
bucket = 'uniquebucketname1234'
 
aws_credentials = {
:aws_access_key_id => 'YOUR-ACCESS-KEY-ID',
:aws_secret_access_key => 'YOUR-SECRET-ACCESS-KEY'
}
 
storage = Fog::Storage.new(aws_credentials.merge(:provider => 'AWS'))
storage.put_bucket(bucket)
 
iam = Fog::AWS::IAM.new(aws_credentials)
 
iam.list_access_keys
 
user_response = iam.create_user(username)
key_response = iam.create_access_key('UserName' => username)
 
access_key_id = key_response.body['AccessKey']['AccessKeyId']
secret_access_key = key_response.body['AccessKey']['SecretAccessKey']
arn = user_response.body['User']['Arn']
 
iam.put_user_policy(username, 'UserKeyPolicy', {
'Statement' => [
'Effect' => 'Allow',
'Action' => 'iam:*AccessKey*',
'Resource' => arn
]
})
 
iam.put_user_policy(username, 'UserS3Policy', {
'Statement' => [
{
'Effect' => 'Allow',
'Action' => ['s3:*'],
'Resource' => [
"arn:aws:s3:::#{bucket}",
"arn:aws:s3:::#{bucket}/*"
]
}, {
'Effect' => 'Deny',
'Action' => ['s3:*'],
'NotResource' => [
"arn:aws:s3:::#{bucket}",
"arn:aws:s3:::#{bucket}/*"
]
}
]
})
 
aws_credentials = {
:aws_access_key_id => access_key_id,
:aws_secret_access_key => secret_access_key
}
 
storage = Fog::Storage.new(aws_credentials.merge(:provider => 'AWS'))
storage.get_bucket(bucket)
storage.put_object(bucket, 'image.png', File.open('/path/to/image.png'))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.