Class: Kybus::AWS::Role

Inherits:
Resource show all
Defined in:
lib/kybus/aws/role.rb

Constant Summary collapse

LAMBDA_ASSUME_ROLE_POLICY =
{
  Version: '2012-10-17',
  Statement: [
    {
      Effect: 'Allow',
      Principal: {
        Service: 'lambda.amazonaws.com'
      },
      Action: 'sts:AssumeRole'
    }
  ]
}.to_json.freeze

Instance Method Summary collapse

Methods inherited from Resource

#account_id, #with_retries

Constructor Details

#initialize(config, name, type) ⇒ Role

Returns a new instance of Role.



19
20
21
22
23
24
25
# File 'lib/kybus/aws/role.rb', line 19

def initialize(config, name, type)
  super(config)
  @type = type
  @name = name
  @iam_client = Aws::IAM::Client.new
  @policies = []
end

Instance Method Details

#add_policy(policy) ⇒ Object



27
28
29
# File 'lib/kybus/aws/role.rb', line 27

def add_policy(policy)
  @policies << policy
end

#assume_role_policyObject



31
32
33
34
35
36
37
38
# File 'lib/kybus/aws/role.rb', line 31

def assume_role_policy
  case @type
  when :lambda
    LAMBDA_ASSUME_ROLE_POLICY
  else
    raise 'Invalid Role Type'
  end
end

#create_or_update!Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/kybus/aws/role.rb', line 40

def create_or_update!
  begin
    @iam_client.create_role({
                              role_name: @name,
                              assume_role_policy_document: assume_role_policy
                            })
    puts "Role '#{@name}' created."
  rescue Aws::IAM::Errors::EntityAlreadyExists
    puts "Role '#{@name}' already exists."
  end

  @policies.each do |policy|
    @iam_client.attach_role_policy(role_name: @name, policy_arn: policy.arn)
    puts "Policy '#{policy.name}' attached to role '#{@name}'."
  rescue Aws::IAM::Errors::EntityAlreadyExists
    puts "Policy '#{policy.name}' already attached to role '#{@name}'."
  end
end

#destroy!Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/kybus/aws/role.rb', line 59

def destroy!
  @policies.each do |policy|
    @iam_client.detach_role_policy({ role_name: @name, policy_arn: policy.arn })
    puts "Policy '#{policy.name}' deleted."
  rescue Aws::IAM::Errors::NoSuchEntity
    puts "Policy '#{policy.name}' not found."
  end

  begin
    @iam_client.delete_role(role_name: @name)
    puts "Role '#{@name}' deleted."
  rescue Aws::IAM::Errors::NoSuchEntity
    puts "Role '#{@name}' not found."
  end
end