Class: BuildCloud::SecurityGroup

Inherits:
Object
  • Object
show all
Includes:
Component
Defined in:
lib/build-cloud/securitygroup.rb

Constant Summary collapse

@@objects =
[]

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Component

included

Constructor Details

#initialize(fog_interfaces, log, options = {}) ⇒ SecurityGroup

Returns a new instance of SecurityGroup.



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/build-cloud/securitygroup.rb', line 25

def initialize ( fog_interfaces, log, options = {} )

    @compute = fog_interfaces[:compute]
    @log     = log
    @options = options

    @log.debug( options.inspect )

    required_options(:name, :description)
    require_one_of(:vpc_id, :vpc_name)

end

Class Method Details

.get_id_by_name(name) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/build-cloud/securitygroup.rb', line 7

def self.get_id_by_name( name )

    sg = self.search( :name => name ).first

    unless sg
        raise "Couldn't get a SecurityGroup object for #{name} - is it defined?"
    end

    sg_fog = sg.read

    unless sg_fog
        raise "Couldn't get a SecurityGroup fog object for #{name} - is it created?"
    end

    sg_fog.group_id

end

Instance Method Details

#createObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/build-cloud/securitygroup.rb', line 38

def create

    options = @options.dup

    authorized_ranges = []
    if options[:authorized_ranges]
        authorized_ranges = options[:authorized_ranges]
        options.delete(:authorized_ranges)
    end

    if exists?
        # If exists update tags
        if options[:tags]
            create_tags(options[:tags])
        end
    else

        @log.info( "Creating security group #{@options[:name]}" )

        unless options[:vpc_id]

            options[:vpc_id] = BuildCloud::VPC.get_id_by_name( options[:vpc_name] )
            options.delete(:vpc_name)

        end

        security_group = @compute.security_groups.new( options )
        security_group.save

        @log.debug( security_group.inspect )

    end

    rationalise_rules( authorized_ranges )

end

#create_tags(tags) ⇒ Object



218
219
220
221
222
223
224
225
# File 'lib/build-cloud/securitygroup.rb', line 218

def create_tags(tags)
    # force symbols to strings in yaml tags
    resolved_tags = fog_object.tags.dup.merge(tags.collect{|k,v| [k.to_s, v]}.to_h)
    if resolved_tags != fog_object.tags
        @log.info("Updating tags for security group #{fog_object.name}")
        @compute.create_tags( fog_object.group_id.to_s, tags )
    end
end

#deleteObject



208
209
210
211
212
213
214
215
216
# File 'lib/build-cloud/securitygroup.rb', line 208

def delete

    return unless exists?

    @log.info( "Deleting security group #{@options[:name]}" )

    fog_object.destroy

end

#rationalise_rules(authorized_ranges) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/build-cloud/securitygroup.rb', line 75

def rationalise_rules( authorized_ranges )

    security_group = read

    current_rules = []
    rules_to_add  = []

    # Read all the existing rules from the SG object. Turn what we find into
    # a list of hashes, where the hash parameter names match those that we use
    # in the YAML description.  This will aid comparison of current vs. desired rules
    
    security_group.ip_permissions.each do |r|

        if r['groups'] != []

            r['groups'].each do |group|

                c = {
                    :min_port    => r['fromPort'],
                    :max_port    => r['toPort'],
                    :ip_protocol => r['ipProtocol'],
                    :name        => @compute.security_groups.select { |sg| sg.group_id == group['groupId'] }.first.name,
                }

                current_rules << c

            end

        end

        if r['ipRanges'] != []

            r['ipRanges'].each do |ipRange|

                c = {
                    :min_port    => r['fromPort'],
                    :max_port    => r['toPort'],
                    :ip_protocol => r['ipProtocol'],
                    :cidr_ip     => ipRange['cidrIp'],
                }

                current_rules << c

            end

        end

    end

    # Work through the list of desired rules.

    authorized_ranges.each do |r|

        # If we find a current rule that matches the desired rule, then
        # remove that from the list of current rules - you'll see why later.

        already_exists = false
        current_rules.delete_if do |c|
           if c == r
              @log.debug ( "#{r.inspect} already exists" )
              already_exists = true
              true # so that delete_if removes the list item
           end 
        end

        unless already_exists

            # If the rule doesn't exist already, flag it to be added.
            # We do this *after* deleting old rules since some changes
            # to existing rules can cause conflict and error.
            # (eg. changing a rule from matching a sg name to matching
            # a cidr block causes this)

            rules_to_add << r

        end

    end

    # At the end of this loop, anything left in the current_rules list
    # represents a rule that's present on the infra, but should be deleted
    # (since there's no matching desired rule), so delete those.
    # Changing a rule maps to "delete old rule, create new one".

    current_rules.each do |r|

        @log.debug ( "Revoking superfluous #{r.inspect}" )

        # Translate sg name into id - looking up with API so we can reference SG names not in the config yaml
        if r.has_key?(:name) 
            groups = @compute.security_groups.select { |sg| sg.name == r[:name] }
            if groups.count == 0
                raise "Can't find security group id for group name '#{r[:name]}'"
            end
            r[:group] = groups.first.group_id
        end


        security_group.revoke_port_range( 
            r.delete(:min_port)..r.delete(:max_port), r
        )

    end

    # Add any new rules that are required.

    rules_to_add.each do |r|

        @log.debug( "Adding #{r.inspect}" )

        # Translate sg name into id - looking up with API so we can reference SG names not in the config yaml
        if r.has_key?(:name) 
            groups = @compute.security_groups.select { |sg| sg.name == r[:name] }
            if groups.count == 0
                raise "Can't find security group id for group name '#{r[:name]}'"
            end
            r[:group] = groups.first.group_id
        end

        security_group.authorize_port_range(
            r.delete(:min_port)..r.delete(:max_port), r
        )

    end

end

#readObject Also known as: fog_object



202
203
204
# File 'lib/build-cloud/securitygroup.rb', line 202

def read
    @compute.security_groups.select { |sg| sg.name == @options[:name] }.first
end