Created
June 3, 2017 16:02
-
-
Save localytics-gist/bcaf9f788cb1a5b6cd4060545449ea1c to your computer and use it in GitHub Desktop.
Cogito backup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'bundler/inline' | |
| gemfile do | |
| source 'https://rubygems.org' | |
| gem 'cogito', '0.2.0' | |
| gem 'aws-sdk', '~> 2.9' | |
| gem 'rubyzip', '>= 1.0.0' | |
| end | |
| require 'json' | |
| require 'zip' | |
| Aws.config[:region] = 'us-east-1' | |
| client = Aws::IAM::Client.new | |
| Zip::File.open('aws-policies.zip', Zip::File::CREATE) do |zipfile| | |
| client.list_policies.each do |response| | |
| response.policies.each do |policy| | |
| encoded = | |
| client.get_policy_version( | |
| policy_arn: policy.arn, | |
| version_id: policy.default_version_id | |
| ).policy_version.document | |
| statements = JSON.parse(URI.decode(encoded))['Statement'] | |
| statements = [statements] unless statements.is_a?(Array) | |
| entry_name = "#{policy.policy_id}-#{policy.policy_name}.iam" | |
| zipfile.get_output_stream(entry_name) do |os| | |
| os.write(Cogito.to_iam(JSON.dump(statements))) | |
| end | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'bundler/inline' | |
| gemfile do | |
| source 'https://rubygems.org' | |
| gem 'cogito', '0.2.0' | |
| gem 'aws-sdk', '~> 2.9' | |
| gem 'rubyzip', '>= 1.0.0' | |
| end | |
| require 'json' | |
| require 'zip' | |
| Aws.config[:region] = 'us-east-1' | |
| client = Aws::IAM::Client.new | |
| Zip::File.open('aws-policies.zip') do |zipfile| | |
| policy_ids = | |
| client.list_policies.flat_map do |response| | |
| response.policies.map(&:policy_id) | |
| end | |
| zipfile.each do |entry| | |
| policy_id, policy_name = File.basename(entry.name, '.iam').split('-', 2) | |
| next if policy_ids.include?(policy_id) | |
| policy_document = { | |
| 'Version': '2012-10-17', | |
| 'Statement': JSON.parse(Cogito.to_json(entry.get_input_stream.read)) | |
| } | |
| new_policy_id = | |
| client.create_policy( | |
| policy_name: policy_name, | |
| policy_document: JSON.dump(policy_document) | |
| ).policy.policy_id | |
| zipfile.rename(entry.name, "#{new_policy_id}-#{policy_name}.iam") | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment