Skip to content

Instantly share code, notes, and snippets.

@benizi
Forked from mndoci/iam_fog.rb
Created December 6, 2013 06:44
Show Gist options
  • Save benizi/7819567 to your computer and use it in GitHub Desktop.
Save benizi/7819567 to your computer and use it in GitHub Desktop.
# via http://blog.zerosum.org/2011/03/02/better-aws-access-control-with-iam-and-fog.html
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_name}",
"arn:aws:s3:::#{bucket_name}/*"
]
}, {
'Effect' => 'Deny',
'Action' => ['s3:*'],
'NotResource' => [
"arn:aws:s3:::#{bucket_name}",
"arn:aws:s3:::#{bucket_name}/*"
]
}
]
})
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'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment