Sha256: f4993a2c3c5afdcc1c31cbf16bd3880786dfb712063d86ed3e0b2b6b263baa0a

Contents?: true

Size: 1.78 KB

Versions: 9

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module PracticeTerraforming
  module Resource
    class S3
      include PracticeTerraforming::Util

      def self.tf(client: Aws::S3::Client.new)
        self.new(client).tf
      end

      def self.tfstate(client: Aws::S3::Client.new)
        self.new(client).tfstate
      end

      def initialize(client)
        @client = client
      end

      def tf
        apply_template(@client, "tf/s3")
      end

      def tfstate
        buckets.inject({}) do |resources, bucket|
          bucket_policy = bucket_policy_of(bucket)
          resources["aws_s3_bucket.#{module_name_of(bucket)}"] = {
            "type" => "aws_s3_bucket",
            "primary" => {
              "id" => bucket.name,
              "attributes" => {
                "acl" => "private",
                "bucket" => bucket.name,
                "force_destroy" => "false",
                "id" => bucket.name,
                "policy" => bucket_policy ? bucket_policy.policy.read : ""
              }
            }
          }

          resources
        end
      end

      private

      def bucket_location_of(bucket)
        @client.get_bucket_location(bucket: bucket.name).location_constraint
      end

      def bucket_policy_of(bucket)
        @client.get_bucket_policy(bucket: bucket.name)
      rescue Aws::S3::Errors::NoSuchBucketPolicy
        nil
      end

      def buckets
        @client.list_buckets.map(&:buckets).flatten.select { |bucket| same_region?(bucket) }
      end

      def module_name_of(bucket)
        normalize_module_name(bucket.name)
      end

      def same_region?(bucket)
        bucket_location = bucket_location_of(bucket)
        (bucket_location == @client.config.region) || (bucket_location == "" && @client.config.region == "us-east-1")
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
practice_terraforming-0.1.11 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.10 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.9 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.8 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.7 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.6 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.5 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.4 lib/practice_terraforming/resource/s3.rb
practice_terraforming-0.1.3 lib/practice_terraforming/resource/s3.rb