From f6cb9bce15ba0201e6a1dc123ba2c29b76151a66 Mon Sep 17 00:00:00 2001 From: lwade Date: Wed, 31 Jul 2013 11:51:57 +0100 Subject: [PATCH] Added ability to create virtual directories. --- library/cloud/s3 | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/library/cloud/s3 b/library/cloud/s3 index cd9d5d4524e..f48ac40ce35 100644 --- a/library/cloud/s3 +++ b/library/cloud/s3 @@ -82,6 +82,8 @@ EXAMPLES = ''' - s3: bucket=mybucket object=/my/desired/key.txt src=/usr/local/myfile.txt mode=put overwrite=true # Create an empty bucket - s3: bucket=mybucket mode=create +# Create a bucket with key as directory +- s3: bucket=mybucket object=/my/directory/path mode=create # Delete a bucket and all contents - s3: bucket=mybucket mode=delete ''' @@ -156,11 +158,12 @@ def delete_key(module, s3, bucket, obj): except s3.provider.storage_response_error, e: module.fail_json(msg= str(e)) -def create_key(module, s3, bucket, obj): +def create_dirkey(module, s3, bucket, obj): try: bucket = s3.lookup(bucket) - bucket.new_key(obj) - module.exit_json(msg="Object %s created in bucket %s" % (obj, bucket), changed=True) + key = bucket.new_key(obj) + key.set_contents_from_string('') + module.exit_json(msg="Virtual directory %s created in bucket %s" % (obj, bucket.name), changed=True) except s3.provider.storage_response_error, e: module.fail_json(msg= str(e)) @@ -372,14 +375,27 @@ def main(): # Need to research how to create directories without "populating" a key, so this should just do bucket creation for now. # WE SHOULD ENABLE SOME WAY OF CREATING AN EMPTY KEY TO CREATE "DIRECTORY" STRUCTURE, AWS CONSOLE DOES THIS. if mode == 'create': - if bucket: + if bucket and not obj: bucketrtn = bucket_check(module, s3, bucket) if bucketrtn is True: module.exit_json(msg="Bucket already exists.", changed=False) else: created = create_bucket(module, s3, bucket) if bucket and obj: - module.fail_json(msg="mode=create can only be used for bucket creation.", failed=True) + bucketrtn = bucket_check(module, s3, bucket) + if obj.endswith('/'): + dirobj = obj + else: + dirobj = obj + "/" + if bucketrtn is True: + keyrtn = key_check(module, s3, bucket, dirobj) + if keyrtn is True: + module.exit_json(msg="Bucket %s and key %s already exists."% (bucket, obj), changed=False) + else: + create_dirkey(module, s3, bucket, dirobj) + if bucketrtn is False: + created = create_bucket(module, s3, bucket) + create_dirkey(module, s3, bucket, dirobj) # Support for grabbing the time-expired URL for an object in S3/Walrus. if mode == 'geturl':