repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/spec/lib/terraforming/resource/security_group_spec.rb
spec/lib/terraforming/resource/security_group_spec.rb
require "spec_helper" module Terraforming module Resource describe SecurityGroup do let(:client) do Aws::EC2::Client.new(stub_responses: true) end let(:security_groups) do [ { owner_id: "012345678901", group_name: "hoge", group_id: "sg-1234abcd", description: "Group for hoge", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, user_id_group_pairs: [], ip_ranges: [ { cidr_ip: "0.0.0.0/0" } ], ipv_6_ranges: [ { cidr_ipv_6: "::/0" } ] }, { ip_protocol: "tcp", from_port: 22, to_port: 22, user_id_group_pairs: [ { user_id: "987654321012", group_id: "sg-9876uxyz", group_name: "piyo" }, { user_id: "012345678901", group_id: "sg-1234abcd", group_name: "hoge" } ], ip_ranges: [], ipv_6_ranges: [] }, ], vpc_id: nil, tags: [] }, { owner_id: "098765432109", group_name: "fuga", group_id: "sg-5678efgh", description: "Group for fuga", vpc_id: "vpc-1234abcd", ip_permissions: [ { ip_protocol: "tcp", from_port: 0, to_port: 65535, user_id_group_pairs: [ { user_id: "098765432109", group_name: nil, group_id: "sg-5678efgh" } ], ip_ranges: [], ipv_6_ranges: [] }, { ip_protocol: "tcp", from_port: 22, to_port: 22, user_id_group_pairs: [ { user_id: "098765432109", group_name: nil, group_id: "sg-1234efgh" } ], ip_ranges: [ { cidr_ip: "0.0.0.0/0" } ], ipv_6_ranges: [ { cidr_ipv_6: "::/0" } ] }, { ip_protocol: "tcp", from_port: 7777, to_port: 7777, user_id_group_pairs: [ { user_id: "098765432109", group_name: nil, group_id: "sg-5678efgh" }, { user_id: "098765432109", group_name: nil, group_id: "sg-7777abcd" } ], ip_ranges: [], ipv_6_ranges: [] }, ], ip_permissions_egress: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, user_id_group_pairs: [ { user_id: "098765432109", group_name: nil, group_id: "sg-5678efgh" }, { user_id: "098765432109", group_name: nil, group_id: "sg-1234efgh" } ], ip_ranges: [ { cidr_ip: "0.0.0.0/0" } ], ipv_6_ranges: [ { cidr_ipv_6: "::/0" } ] }, ], tags: [ { key: "Name", value: "fuga" } ] }, { owner_id: "098765432109", group_name: "piyo", group_id: "sg-9012ijkl", description: "Group for piyo", vpc_id: "vpc-1234abcd", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, user_id_group_pairs: [ { user_id: "098765432109", group_name: nil, group_id: "sg-9012ijkl" } ], ip_ranges: [], ipv_6_ranges: [] }, { ip_protocol: "tcp", from_port: 22, to_port: 22, user_id_group_pairs: [], ip_ranges: [ { cidr_ip: "0.0.0.0/0" } ], ipv_6_ranges: [ { cidr_ipv_6: "::/0" } ] }, ], ip_permissions_egress: [ { ip_protocol: "-1", from_port: 1, to_port: 65535, user_id_group_pairs: [], ip_ranges: [ { cidr_ip: "0.0.0.0/0" } ], ipv_6_ranges: [ { cidr_ipv_6: "::/0" } ], prefix_list_ids: [ { prefix_list_id: "pl-xxxxxx" } ], }, ], tags: [ { key: "Name", value: "piyo" } ] } ] end before do client.stub_responses(:describe_security_groups, security_groups: security_groups) end describe ".tf" do it "should generate tf" do expect(described_class.tf(client: client)).to eq <<-EOS resource "aws_security_group" "hoge" { name = "hoge" description = "Group for hoge" vpc_id = "" ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } ingress { from_port = 22 to_port = 22 protocol = "tcp" security_groups = ["987654321012/piyo"] self = true } } resource "aws_security_group" "vpc-1234abcd-fuga" { name = "fuga" description = "Group for fuga" vpc_id = "vpc-1234abcd" ingress { from_port = 0 to_port = 65535 protocol = "tcp" security_groups = [] self = true } ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] security_groups = ["sg-1234efgh"] self = false } ingress { from_port = 7777 to_port = 7777 protocol = "tcp" security_groups = ["sg-7777abcd"] self = true } egress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] security_groups = ["sg-1234efgh"] self = true } tags { "Name" = "fuga" } } resource "aws_security_group" "vpc-1234abcd-piyo" { name = "piyo" description = "Group for piyo" vpc_id = "vpc-1234abcd" ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] security_groups = [] self = true } egress { from_port = 1 to_port = 65535 protocol = "-1" prefix_list_ids = ["pl-xxxxxx"] cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } tags { "Name" = "piyo" } } EOS end end describe ".tfstate" do it "should generate tfstate" do expect(described_class.tfstate(client: client)).to eq({ "aws_security_group.hoge" => { "type" => "aws_security_group", "primary" => { "id" => "sg-1234abcd", "attributes" => { "description" => "Group for hoge", "id" => "sg-1234abcd", "name" => "hoge", "owner_id" => "012345678901", "tags.#" => "0", "vpc_id" => "", "egress.#" => "0", "ingress.#" => "2", "ingress.31326685.cidr_blocks.#" => "1", "ingress.31326685.cidr_blocks.0" => "0.0.0.0/0", "ingress.31326685.from_port" => "22", "ingress.31326685.ipv6_cidr_blocks.#" => "1", "ingress.31326685.ipv6_cidr_blocks.0" => "::/0", "ingress.31326685.prefix_list_ids.#" => "0", "ingress.31326685.protocol" => "tcp", "ingress.31326685.security_groups.#" => "0", "ingress.31326685.self" => "false", "ingress.31326685.to_port" => "22", "ingress.3232230010.cidr_blocks.#" => "0", "ingress.3232230010.from_port" => "22", "ingress.3232230010.ipv6_cidr_blocks.#" => "0", "ingress.3232230010.prefix_list_ids.#" => "0", "ingress.3232230010.protocol" => "tcp", "ingress.3232230010.security_groups.#" => "1", "ingress.3232230010.security_groups.1889292513" => "987654321012/piyo", "ingress.3232230010.self" => "true", "ingress.3232230010.to_port" => "22" } } }, "aws_security_group.vpc-1234abcd-fuga" => { "type" => "aws_security_group", "primary" => { "id" => "sg-5678efgh", "attributes" => { "description" => "Group for fuga", "id" => "sg-5678efgh", "name" => "fuga", "owner_id" => "098765432109", "tags.#" => "1", "tags.Name" => "fuga", "vpc_id" => "vpc-1234abcd", "egress.#" => "1", "egress.2007587753.cidr_blocks.#" => "1", "egress.2007587753.cidr_blocks.0" => "0.0.0.0/0", "egress.2007587753.from_port" => "22", "egress.2007587753.ipv6_cidr_blocks.#" => "1", "egress.2007587753.ipv6_cidr_blocks.0" => "::/0", "egress.2007587753.prefix_list_ids.#" => "0", "egress.2007587753.protocol" => "tcp", "egress.2007587753.security_groups.#" => "1", "egress.2007587753.security_groups.3311523735" => "sg-1234efgh", "egress.2007587753.self" => "true", "egress.2007587753.to_port" => "22", "ingress.#" => "3", "ingress.1728187046.cidr_blocks.#" => "0", "ingress.1728187046.from_port" => "7777", "ingress.1728187046.ipv6_cidr_blocks.#" => "0", "ingress.1728187046.prefix_list_ids.#" => "0", "ingress.1728187046.protocol" => "tcp", "ingress.1728187046.security_groups.#" => "1", "ingress.1728187046.security_groups.1756790741" => "sg-7777abcd", "ingress.1728187046.self" => "true", "ingress.1728187046.to_port" => "7777", "ingress.1849628954.cidr_blocks.#" => "0", "ingress.1849628954.from_port" => "0", "ingress.1849628954.ipv6_cidr_blocks.#" => "0", "ingress.1849628954.prefix_list_ids.#" => "0", "ingress.1849628954.protocol" => "tcp", "ingress.1849628954.security_groups.#" => "0", "ingress.1849628954.self" => "true", "ingress.1849628954.to_port" => "65535", "ingress.2890765491.cidr_blocks.#" => "1", "ingress.2890765491.cidr_blocks.0" => "0.0.0.0/0", "ingress.2890765491.from_port" => "22", "ingress.2890765491.ipv6_cidr_blocks.#" => "1", "ingress.2890765491.ipv6_cidr_blocks.0" => "::/0", "ingress.2890765491.prefix_list_ids.#" => "0", "ingress.2890765491.protocol" => "tcp", "ingress.2890765491.security_groups.#" => "1", "ingress.2890765491.security_groups.3311523735" => "sg-1234efgh", "ingress.2890765491.self" => "false", "ingress.2890765491.to_port" => "22" }, } }, "aws_security_group.vpc-1234abcd-piyo" => { "type" => "aws_security_group", "primary"=>{ "id" => "sg-9012ijkl", "attributes"=>{ "description" => "Group for piyo", "id" => "sg-9012ijkl", "name" => "piyo", "owner_id" => "098765432109", "tags.#" => "1", "tags.Name" => "piyo", "vpc_id" => "vpc-1234abcd", "egress.#" => "1", "egress.3936132414.cidr_blocks.#" => "1", "egress.3936132414.cidr_blocks.0" => "0.0.0.0/0", "egress.3936132414.from_port" => "1", "egress.3936132414.ipv6_cidr_blocks.#" => "1", "egress.3936132414.ipv6_cidr_blocks.0" => "::/0", "egress.3936132414.prefix_list_ids.#" => "1", "egress.3936132414.prefix_list_ids.0" => "pl-xxxxxx", "egress.3936132414.protocol" => "-1", "egress.3936132414.security_groups.#" => "0", "egress.3936132414.self" => "false", "egress.3936132414.to_port" => "65535", "ingress.#" => "1", "ingress.3239858.cidr_blocks.#" => "1", "ingress.3239858.cidr_blocks.0" => "0.0.0.0/0", "ingress.3239858.from_port" => "22", "ingress.3239858.ipv6_cidr_blocks.#" => "1", "ingress.3239858.ipv6_cidr_blocks.0" => "::/0", "ingress.3239858.prefix_list_ids.#" => "0", "ingress.3239858.protocol" => "tcp", "ingress.3239858.security_groups.#" => "0", "ingress.3239858.self" => "true", "ingress.3239858.to_port" => "22" } } } }) end end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/spec/lib/terraforming/resource/route53_record_spec.rb
spec/lib/terraforming/resource/route53_record_spec.rb
require "spec_helper" module Terraforming module Resource describe Route53Record do let(:client) do Aws::Route53::Client.new(stub_responses: true) end let(:hosted_zones) do [ { id: "/hostedzone/ABCDEFGHIJKLMN", name: "hoge.net.", caller_reference: "ABCDEFGH-1234-IJKL-5678-MNOPQRSTUVWX", config: { private_zone: false }, resource_record_set_count: 4 }, { id: "/hostedzone/OPQRSTUVWXYZAB", name: "fuga.net.", caller_reference: "ABCDEFGH-5678-IJKL-9012-MNOPQRSTUVWX", config: { private_zone: false }, resource_record_set_count: 4 }, { id: "/hostedzone/CDEFGHIJKLMNOP", name: "example.net.", caller_reference: "ABCDEFGH-9012-IJKL-9012-MNOPQRSTUVWX", config: { private_zone: false }, resource_record_set_count: 4 }, ] end let(:hoge_resource_record_sets) do [ { name: "hoge.net.", type: "A", ttl: 3600, weight: nil, set_identifier: "dev", resource_records: [ { value: "123.456.78.90" }, { value: "hoge.awsdns-60.org" }, ], } ] end let(:fuga_resource_record_sets) do [ { name: "www.fuga.net.", type: "A", ttl: nil, weight: 10, set_identifier: nil, alias_target: { hosted_zone_id: "ABCDEFGHIJ1234", dns_name: "fuga.net.", evaluate_target_health: false, }, } ] end let(:piyo_resource_record_sets) do [ { name: '\052.example.net.', type: "CNAME", ttl: 3600, weight: nil, set_identifier: nil, resource_records: [ { value: "example.com" } ] }, { name: "geo.example.net.", type: "A", ttl: 3600, weight: nil, set_identifier: nil, geo_location: { continent_code: "AS", country_code: "JP", }, }, { name: "geo.example.net.", type: "A", ttl: 60, weight: nil, set_identifier: nil, }, { name: "failover.example.net.", type: "A", ttl: 3600, weight: nil, set_identifier: "failover_group", health_check_id: "1234abcd-56ef-78gh-90ij-123456klmnop", resource_records: [ { value: "192.0.2.101" } ], failover: "PRIMARY" }, { name: "failover.example.net.", type: "A", ttl: 3600, weight: nil, set_identifier: "failover_group", resource_records: [ { value: "192.0.2.102" } ], failover: "SECONDARY" }, ] end before do client.stub_responses(:list_hosted_zones, hosted_zones: hosted_zones, marker: "", is_truncated: false, max_items: 1) client.stub_responses(:list_resource_record_sets, [ { resource_record_sets: hoge_resource_record_sets, is_truncated: false, max_items: 1 }, { resource_record_sets: fuga_resource_record_sets, is_truncated: false, max_items: 1 }, { resource_record_sets: piyo_resource_record_sets, is_truncated: false, max_items: 1 }, ]) end describe ".tf" do it "should generate tf" do expect(described_class.tf(client: client)).to eq <<-EOS resource "aws_route53_record" "hoge-net-A" { zone_id = "ABCDEFGHIJKLMN" name = "hoge.net" type = "A" records = ["123.456.78.90", "hoge.awsdns-60.org"] ttl = "3600" set_identifier = "dev" } resource "aws_route53_record" "www-fuga-net-A" { zone_id = "OPQRSTUVWXYZAB" name = "www.fuga.net" type = "A" weighted_routing_policy { weight = 10 } alias { name = "fuga.net" zone_id = "ABCDEFGHIJ1234" evaluate_target_health = false } } resource "aws_route53_record" "wildcard-example-net-CNAME" { zone_id = "CDEFGHIJKLMNOP" name = "*.example.net" type = "CNAME" records = ["example.com"] ttl = "3600" } resource "aws_route53_record" "geo-example-net-A-0" { zone_id = "CDEFGHIJKLMNOP" name = "geo.example.net" type = "A" ttl = "3600" geolocation_routing_policy { continent = "AS" country = "JP" } } resource "aws_route53_record" "geo-example-net-A-1" { zone_id = "CDEFGHIJKLMNOP" name = "geo.example.net" type = "A" ttl = "60" } resource "aws_route53_record" "failover-example-net-A-0" { zone_id = "CDEFGHIJKLMNOP" name = "failover.example.net" type = "A" records = ["192.0.2.101"] ttl = "3600" set_identifier = "failover_group" health_check_id = "1234abcd-56ef-78gh-90ij-123456klmnop" failover_routing_policy { type = "PRIMARY" } } resource "aws_route53_record" "failover-example-net-A-1" { zone_id = "CDEFGHIJKLMNOP" name = "failover.example.net" type = "A" records = ["192.0.2.102"] ttl = "3600" set_identifier = "failover_group" failover_routing_policy { type = "SECONDARY" } } EOS end end describe ".tfstate" do it "should generate tfstate" do expect(described_class.tfstate(client: client)).to eq({ "aws_route53_record.hoge-net-A" => { "type" => "aws_route53_record", "primary" => { "id" => "ABCDEFGHIJKLMN_hoge.net_A", "attributes" => { "id" => "ABCDEFGHIJKLMN_hoge.net_A", "name" => "hoge.net", "type" => "A", "zone_id" => "ABCDEFGHIJKLMN", "records.#" => "2", "ttl" => "3600", "set_identifier" => "dev", "weight" => "-1", }, } }, "aws_route53_record.www-fuga-net-A" => { "type" => "aws_route53_record", "primary" => { "id" => "OPQRSTUVWXYZAB_www.fuga.net_A", "attributes" => { "id" => "OPQRSTUVWXYZAB_www.fuga.net_A", "name" => "www.fuga.net", "type" => "A", "zone_id" => "OPQRSTUVWXYZAB", "alias.#" => "1", "weight" => "10", }, } }, "aws_route53_record.wildcard-example-net-CNAME" => { "type" => "aws_route53_record", "primary" => { "id" => "CDEFGHIJKLMNOP_*.example.net_CNAME", "attributes" => { "id" => "CDEFGHIJKLMNOP_*.example.net_CNAME", "name" => "*.example.net", "type" => "CNAME", "zone_id" => "CDEFGHIJKLMNOP", "records.#" => "1", "ttl" => "3600", "weight" => "-1", }, } }, "aws_route53_record.geo-example-net-A-0" => { "type" => "aws_route53_record", "primary" => { "id" => "CDEFGHIJKLMNOP_geo.example.net_A", "attributes" => { "id" => "CDEFGHIJKLMNOP_geo.example.net_A", "name" => "geo.example.net", "type" => "A", "zone_id" => "CDEFGHIJKLMNOP", "weight" => "-1", "ttl" => "3600", "continent" => "AS", "country" => "JP", }, } }, "aws_route53_record.geo-example-net-A-1" => { "type" => "aws_route53_record", "primary" => { "id" => "CDEFGHIJKLMNOP_geo.example.net_A", "attributes" => { "id" => "CDEFGHIJKLMNOP_geo.example.net_A", "name" => "geo.example.net", "type" => "A", "zone_id" => "CDEFGHIJKLMNOP", "weight" => "-1", "ttl" => "60", }, } }, "aws_route53_record.failover-example-net-A-0" => { "type" => "aws_route53_record", "primary" => { "id" => "CDEFGHIJKLMNOP_failover.example.net_A", "attributes" => { "failover_routing_policy.#" => "1", "failover_routing_policy.0.type" => "PRIMARY", "health_check_id" => "1234abcd-56ef-78gh-90ij-123456klmnop", "id" => "CDEFGHIJKLMNOP_failover.example.net_A", "name" => "failover.example.net", "type" => "A", "zone_id" => "CDEFGHIJKLMNOP", "records.#" => "1", "weight" => "-1", "ttl" => "3600", "set_identifier" => "failover_group", }, } }, "aws_route53_record.failover-example-net-A-1" => { "type" => "aws_route53_record", "primary" => { "id" => "CDEFGHIJKLMNOP_failover.example.net_A", "attributes" => { "failover_routing_policy.#" => "1", "failover_routing_policy.0.type" => "SECONDARY", "id" => "CDEFGHIJKLMNOP_failover.example.net_A", "name" => "failover.example.net", "type" => "A", "zone_id" => "CDEFGHIJKLMNOP", "records.#" => "1", "weight" => "-1", "ttl" => "3600", "set_identifier" => "failover_group", }, } }, }) end end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/spec/lib/terraforming/resource/iam_group_policy_spec.rb
spec/lib/terraforming/resource/iam_group_policy_spec.rb
require "spec_helper" module Terraforming module Resource describe IAMGroupPolicy do let(:client) do Aws::IAM::Client.new(stub_responses: true) end let(:groups) do [ { path: "/", group_name: "hoge", group_id: "ABCDEFGHIJKLMN1234567", arn: "arn:aws:iam::123456789012:group/hoge", create_date: Time.parse("2015-04-01 12:34:56 UTC"), }, { path: "/system/", group_name: "fuga", group_id: "OPQRSTUVWXYZA8901234", arn: "arn:aws:iam::345678901234:group/fuga", create_date: Time.parse("2015-05-01 12:34:56 UTC"), }, ] end let(:hoge_policy) do { group_name: "hoge", policy_name: "hoge_policy", policy_document: "%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0A%20%20%22Statement%22%3A%20%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%22Action%22%3A%20%5B%0A%20%20%20%20%20%20%20%20%22ec2%3ADescribe%2A%22%0A%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0A%20%20%20%20%20%20%22Resource%22%3A%20%22%2A%22%0A%20%20%20%20%7D%0A%20%20%5D%0A%7D%0A", } end let(:fuga_policy) do { group_name: "fuga", policy_name: "fuga_policy", policy_document: "%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0A%20%20%22Statement%22%3A%20%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%22Action%22%3A%20%5B%0A%20%20%20%20%20%20%20%20%22ec2%3ADescribe%2A%22%0A%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0A%20%20%20%20%20%20%22Resource%22%3A%20%22%2A%22%0A%20%20%20%20%7D%0A%20%20%5D%0A%7D%0A", } end before do client.stub_responses(:list_groups, groups: groups) client.stub_responses(:list_group_policies, [{ policy_names: %w(hoge_policy) }, { policy_names: %w(fuga_policy) }]) client.stub_responses(:get_group_policy, [hoge_policy, fuga_policy]) end describe ".tf" do it "should generate tf" do expect(described_class.tf(client: client)).to eq <<-EOS resource "aws_iam_group_policy" "hoge_hoge_policy" { name = "hoge_policy" group = "hoge" policy = <<POLICY { "Version": "2012-10-17", "Statement": [ { "Action": [ "ec2:Describe*" ], "Effect": "Allow", "Resource": "*" } ] } POLICY } resource "aws_iam_group_policy" "fuga_fuga_policy" { name = "fuga_policy" group = "fuga" policy = <<POLICY { "Version": "2012-10-17", "Statement": [ { "Action": [ "ec2:Describe*" ], "Effect": "Allow", "Resource": "*" } ] } POLICY } EOS end end describe ".tfstate" do it "should generate tfstate" do expect(described_class.tfstate(client: client)).to eq({ "aws_iam_group_policy.hoge_hoge_policy" => { "type" => "aws_iam_group_policy", "primary" => { "id" => "hoge:hoge_policy", "attributes" => { "group" => "hoge", "id" => "hoge:hoge_policy", "name" => "hoge_policy", "policy" => "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": [\n \"ec2:Describe*\"\n ],\n \"Effect\": \"Allow\",\n \"Resource\": \"*\"\n }\n ]\n}\n", } } }, "aws_iam_group_policy.fuga_fuga_policy" => { "type" => "aws_iam_group_policy", "primary" => { "id" => "fuga:fuga_policy", "attributes" => { "group" => "fuga", "id" => "fuga:fuga_policy", "name" => "fuga_policy", "policy" => "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": [\n \"ec2:Describe*\"\n ],\n \"Effect\": \"Allow\",\n \"Resource\": \"*\"\n }\n ]\n}\n", } } } }) end end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming.rb
lib/terraforming.rb
require "aws-sdk-autoscaling" require "aws-sdk-cloudwatch" require "aws-sdk-dynamodb" require "aws-sdk-ec2" require "aws-sdk-efs" require "aws-sdk-elasticache" require "aws-sdk-elasticloadbalancing" require "aws-sdk-elasticloadbalancingv2" require "aws-sdk-iam" require "aws-sdk-kms" require "aws-sdk-rds" require "aws-sdk-redshift" require "aws-sdk-route53" require "aws-sdk-s3" require "aws-sdk-sns" require "aws-sdk-sqs" require "erb" require "multi_json" require "thor" require "zlib" require "terraforming/util" require "terraforming/version" require "terraforming/cli" require "terraforming/resource/alb" require "terraforming/resource/auto_scaling_group" require "terraforming/resource/cloud_watch_alarm" require "terraforming/resource/db_parameter_group" require "terraforming/resource/db_security_group" require "terraforming/resource/db_subnet_group" require "terraforming/resource/dynamo_db" require "terraforming/resource/ec2" require "terraforming/resource/eip" require "terraforming/resource/elasti_cache_cluster" require "terraforming/resource/elasti_cache_subnet_group" require "terraforming/resource/efs_file_system" require "terraforming/resource/elb" require "terraforming/resource/iam_group" require "terraforming/resource/iam_group_membership" require "terraforming/resource/iam_group_policy" require "terraforming/resource/iam_instance_profile" require "terraforming/resource/iam_policy" require "terraforming/resource/iam_policy_attachment" require "terraforming/resource/iam_role" require "terraforming/resource/iam_role_policy" require "terraforming/resource/iam_user" require "terraforming/resource/iam_user_policy" require "terraforming/resource/kms_alias" require "terraforming/resource/kms_key" require "terraforming/resource/launch_configuration" require "terraforming/resource/internet_gateway" require "terraforming/resource/nat_gateway" require "terraforming/resource/network_acl" require "terraforming/resource/network_interface" require "terraforming/resource/rds" require "terraforming/resource/redshift" require "terraforming/resource/route_table" require "terraforming/resource/route_table_association" require "terraforming/resource/route53_record" require "terraforming/resource/route53_zone" require "terraforming/resource/s3" require "terraforming/resource/security_group" require "terraforming/resource/subnet" require "terraforming/resource/sqs" require "terraforming/resource/vpc" require "terraforming/resource/vpn_gateway" require "terraforming/resource/sns_topic" require "terraforming/resource/sns_topic_subscription"
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/version.rb
lib/terraforming/version.rb
module Terraforming VERSION = "0.18.0" end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/cli.rb
lib/terraforming/cli.rb
module Terraforming class CLI < Thor class_option :merge, type: :string, desc: "tfstate file to merge" class_option :overwrite, type: :boolean, desc: "Overwrite existing tfstate" class_option :tfstate, type: :boolean, desc: "Generate tfstate" class_option :profile, type: :string, desc: "AWS credentials profile" class_option :region, type: :string, desc: "AWS region" class_option :assume, type: :string, desc: "Role ARN to assume" class_option :use_bundled_cert, type: :boolean, desc: "Use the bundled CA certificate from AWS SDK" desc "alb", "ALB" def alb execute(Terraforming::Resource::ALB, options) end desc "asg", "AutoScaling Group" def asg execute(Terraforming::Resource::AutoScalingGroup, options) end desc "cwa", "CloudWatch Alarm" def cwa execute(Terraforming::Resource::CloudWatchAlarm, options) end desc "dbpg", "Database Parameter Group" def dbpg execute(Terraforming::Resource::DBParameterGroup, options) end desc "dbsg", "Database Security Group" def dbsg execute(Terraforming::Resource::DBSecurityGroup, options) end desc "dbsn", "Database Subnet Group" def dbsn execute(Terraforming::Resource::DBSubnetGroup, options) end desc "ddb", "DynamoDB" def ddb execute(Terraforming::Resource::DynamoDB, options) end desc "ec2", "EC2" def ec2 execute(Terraforming::Resource::EC2, options) end desc "ecc", "ElastiCache Cluster" def ecc execute(Terraforming::Resource::ElastiCacheCluster, options) end desc "ecsn", "ElastiCache Subnet Group" def ecsn execute(Terraforming::Resource::ElastiCacheSubnetGroup, options) end desc "eip", "EIP" def eip execute(Terraforming::Resource::EIP, options) end desc "efs", "EFS File System" def efs execute(Terraforming::Resource::EFSFileSystem, options) end desc "elb", "ELB" def elb execute(Terraforming::Resource::ELB, options) end desc "iamg", "IAM Group" def iamg execute(Terraforming::Resource::IAMGroup, options) end desc "iamgm", "IAM Group Membership" def iamgm execute(Terraforming::Resource::IAMGroupMembership, options) end desc "iamgp", "IAM Group Policy" def iamgp execute(Terraforming::Resource::IAMGroupPolicy, options) end desc "iamip", "IAM Instance Profile" def iamip execute(Terraforming::Resource::IAMInstanceProfile, options) end desc "iamp", "IAM Policy" def iamp execute(Terraforming::Resource::IAMPolicy, options) end desc "iampa", "IAM Policy Attachment" def iampa execute(Terraforming::Resource::IAMPolicyAttachment, options) end desc "iamr", "IAM Role" def iamr execute(Terraforming::Resource::IAMRole, options) end desc "iamrp", "IAM Role Policy" def iamrp execute(Terraforming::Resource::IAMRolePolicy, options) end desc "iamu", "IAM User" def iamu execute(Terraforming::Resource::IAMUser, options) end desc "iamup", "IAM User Policy" def iamup execute(Terraforming::Resource::IAMUserPolicy, options) end desc "kmsa", "KMS Key Alias" def kmsa execute(Terraforming::Resource::KMSAlias, options) end desc "kmsk", "KMS Key" def kmsk execute(Terraforming::Resource::KMSKey, options) end desc "lc", "Launch Configuration" def lc execute(Terraforming::Resource::LaunchConfiguration, options) end desc "igw", "Internet Gateway" def igw execute(Terraforming::Resource::InternetGateway, options) end desc "nacl", "Network ACL" def nacl execute(Terraforming::Resource::NetworkACL, options) end desc "nat", "NAT Gateway" def nat execute(Terraforming::Resource::NATGateway, options) end desc "nif", "Network Interface" def nif execute(Terraforming::Resource::NetworkInterface, options) end desc "r53r", "Route53 Record" def r53r execute(Terraforming::Resource::Route53Record, options) end desc "r53z", "Route53 Hosted Zone" def r53z execute(Terraforming::Resource::Route53Zone, options) end desc "rds", "RDS" def rds execute(Terraforming::Resource::RDS, options) end desc "rs", "Redshift" def rs execute(Terraforming::Resource::Redshift, options) end desc "rt", "Route Table" def rt execute(Terraforming::Resource::RouteTable, options) end desc "rta", "Route Table Association" def rta execute(Terraforming::Resource::RouteTableAssociation, options) end desc "s3", "S3" def s3 execute(Terraforming::Resource::S3, options) end desc "sg", "Security Group" def sg execute(Terraforming::Resource::SecurityGroup, options) end desc "sn", "Subnet" def sn execute(Terraforming::Resource::Subnet, options) end desc "sqs", "SQS" def sqs execute(Terraforming::Resource::SQS, options) end desc "vpc", "VPC" def vpc execute(Terraforming::Resource::VPC, options) end desc "vgw", "VPN Gateway" def vgw execute(Terraforming::Resource::VPNGateway, options) end desc "snst", "SNS Topic" def snst execute(Terraforming::Resource::SNSTopic, options) end desc "snss", "SNS Subscription" def snss execute(Terraforming::Resource::SNSTopicSubscription, options) end private def configure_aws(options) Aws.config[:credentials] = Aws::SharedCredentials.new(profile_name: options[:profile]) if options[:profile] Aws.config[:region] = options[:region] if options[:region] if options[:assume] args = { role_arn: options[:assume], role_session_name: "terraforming-session-#{Time.now.to_i}" } args[:client] = Aws::STS::Client.new(profile: options[:profile]) if options[:profile] Aws.config[:credentials] = Aws::AssumeRoleCredentials.new(args) end Aws.use_bundled_cert! if options[:use_bundled_cert] end def execute(klass, options) configure_aws(options) result = options[:tfstate] ? tfstate(klass, options[:merge]) : tf(klass) if options[:tfstate] && options[:merge] && options[:overwrite] open(options[:merge], "w+") do |f| f.write(result) f.flush end else puts result end end def tf(klass) klass.tf end def tfstate(klass, tfstate_path) tfstate = tfstate_path ? MultiJson.load(open(tfstate_path).read) : tfstate_skeleton tfstate["serial"] = tfstate["serial"] + 1 tfstate["modules"][0]["resources"] = tfstate["modules"][0]["resources"].merge(klass.tfstate) MultiJson.encode(tfstate, pretty: true) end def tfstate_skeleton { "version" => 1, "serial" => 0, "modules" => [ { "path" => [ "root" ], "outputs" => {}, "resources" => {}, } ] } end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/util.rb
lib/terraforming/util.rb
module Terraforming module Util def apply_template(client, erb) ERB.new(open(template_path(erb)).read, nil, "-").result(binding) end def name_from_tag(resource, default_name) name_tag = resource.tags.find { |tag| tag.key == "Name" } name_tag ? name_tag.value : default_name end def normalize_module_name(name) name.gsub(/[^a-zA-Z0-9_-]/, "-") end def template_path(template_name) File.join(File.expand_path(File.dirname(__FILE__)), "template", template_name) << ".erb" end def prettify_policy(document, breakline: false, unescape: false) json = JSON.pretty_generate(JSON.parse(unescape ? CGI.unescape(document) : document)) if breakline json[-1] != "\n" ? json << "\n" : json else json.strip end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/subnet.rb
lib/terraforming/resource/subnet.rb
module Terraforming module Resource class Subnet include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/subnet") end def tfstate subnets.inject({}) do |resources, subnet| attributes = { "availability_zone" => subnet.availability_zone, "cidr_block" => subnet.cidr_block, "id" => subnet.subnet_id, "map_public_ip_on_launch" => subnet.map_public_ip_on_launch.to_s, "tags.#" => subnet.tags.length.to_s, "vpc_id" => subnet.vpc_id, } resources["aws_subnet.#{module_name_of(subnet)}"] = { "type" => "aws_subnet", "primary" => { "id" => subnet.subnet_id, "attributes" => attributes } } resources end end private def subnets @client.describe_subnets.map(&:subnets).flatten end def module_name_of(subnet) normalize_module_name("#{subnet.subnet_id}-#{name_from_tag(subnet, subnet.subnet_id)}") end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/sqs.rb
lib/terraforming/resource/sqs.rb
module Terraforming module Resource class SQS include Terraforming::Util def self.tf(client: Aws::SQS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::SQS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/sqs") end def tfstate queues.inject({}) do |resources, queue| attributes = { "name" => module_name_of(queue), "id" => queue["QueueUrl"], "arn" => queue["QueueArn"], "visibility_timeout_seconds" => queue["VisibilityTimeout"], "message_retention_seconds" => queue["MessageRetentionPeriod"], "max_message_size" => queue["MaximumMessageSize"], "delay_seconds" => queue["DelaySeconds"], "receive_wait_time_seconds" => queue["ReceiveMessageWaitTimeSeconds"], "policy" => queue.key?("Policy") ? queue["Policy"] : "", "redrive_policy" => queue.key?("RedrivePolicy") ? queue["RedrivePolicy"] : "", } resources["aws_sqs_queue.#{module_name_of(queue)}"] = { "type" => "aws_sqs_queue", "primary" => { "id" => queue["QueueUrl"], "attributes" => attributes, } } resources end end private def queues queue_urls.map do |queue_url| attributes = @client.get_queue_attributes({ queue_url: queue_url, attribute_names: ["All"], }).attributes attributes["QueueUrl"] = queue_url attributes end end def queue_urls @client.list_queues.map(&:queue_urls).flatten end def module_name_of(queue) normalize_module_name(queue["QueueArn"].split(":").last) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/db_parameter_group.rb
lib/terraforming/resource/db_parameter_group.rb
module Terraforming module Resource class DBParameterGroup include Terraforming::Util def self.tf(client: Aws::RDS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::RDS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/db_parameter_group") end def tfstate db_parameter_groups.inject({}) do |resources, parameter_group| attributes = { "description" => parameter_group.description, "family" => parameter_group.db_parameter_group_family, "id" => parameter_group.db_parameter_group_name, "name" => parameter_group.db_parameter_group_name, "parameter.#" => db_parameters_in(parameter_group).length.to_s } resources["aws_db_parameter_group.#{module_name_of(parameter_group)}"] = { "type" => "aws_db_parameter_group", "primary" => { "id" => parameter_group.db_parameter_group_name, "attributes" => attributes } } resources end end private def db_parameter_groups @client.describe_db_parameter_groups.map(&:db_parameter_groups).flatten end def db_parameters_in(parameter_group) @client.describe_db_parameters(db_parameter_group_name: parameter_group.db_parameter_group_name).map(&:parameters).flatten end def module_name_of(parameter_group) normalize_module_name(parameter_group.db_parameter_group_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_instance_profile.rb
lib/terraforming/resource/iam_instance_profile.rb
module Terraforming module Resource class IAMInstanceProfile include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_instance_profile") end def tfstate iam_instance_profiles.inject({}) do |resources, profile| attributes = { "arn" => profile.arn, "id" => profile.instance_profile_name, "name" => profile.instance_profile_name, "path" => profile.path, "role" => profile.roles[0].role_name, "roles.#" => profile.roles.length.to_s, } resources["aws_iam_instance_profile.#{module_name_of(profile)}"] = { "type" => "aws_iam_instance_profile", "primary" => { "id" => profile.instance_profile_name, "attributes" => attributes } } resources end end private def iam_instance_profiles @client.list_instance_profiles.map(&:instance_profiles).flatten end def module_name_of(profile) normalize_module_name(profile.instance_profile_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/route53_record.rb
lib/terraforming/resource/route53_record.rb
module Terraforming module Resource class Route53Record include Terraforming::Util def self.tf(client: Aws::Route53::Client.new) self.new(client).tf end def self.tfstate(client: Aws::Route53::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/route53_record") end def tfstate records.inject({}) do |resources, r| record, zone_id = r[:record], r[:zone_id] counter = r[:counter] record_id = record_id_of(record, zone_id) attributes = { "id" => record_id, "name" => name_of(record.name.gsub(/\\052/, '*')), "type" => record.type, "zone_id" => zone_id, } attributes["alias.#"] = "1" if record.alias_target attributes["records.#"] = record.resource_records.length.to_s unless record.resource_records.empty? attributes["ttl"] = record.ttl.to_s if record.ttl attributes["weight"] = record.weight ? record.weight.to_s : "-1" attributes["region"] = record.region if record.region if record.geo_location attributes["continent"] = record.geo_location.continent_code if record.geo_location.continent_code attributes["country"] = record.geo_location.country_code if record.geo_location.country_code attributes["subdivision"] = record.geo_location.subdivision_code if record.geo_location.subdivision_code end if record.failover attributes["failover_routing_policy.#"] = "1" attributes["failover_routing_policy.0.type"] = record.failover end attributes["set_identifier"] = record.set_identifier if record.set_identifier attributes["health_check_id"] = record.health_check_id if record.health_check_id resources["aws_route53_record.#{module_name_of(record, counter)}"] = { "type" => "aws_route53_record", "primary" => { "id" => record_id, "attributes" => attributes, } } resources end end private def hosted_zones @client.list_hosted_zones.map(&:hosted_zones).flatten end def record_id_of(record, zone_id) "#{zone_id}_#{name_of(record.name.gsub(/\\052/, '*'))}_#{record.type}" end def record_sets_of(hosted_zone) @client.list_resource_record_sets(hosted_zone_id: zone_id_of(hosted_zone)).map do |response| response.data.resource_record_sets end.flatten end def records to_return = hosted_zones.map do |hosted_zone| record_sets_of(hosted_zone).map { |record| { record: record, zone_id: zone_id_of(hosted_zone) } } end.flatten count = {} dups = to_return.group_by { |record| module_name_of(record[:record], nil) }.select { |_, v| v.size > 1 }.map(&:first) to_return.each do |r| module_name = module_name_of(r[:record], nil) next unless dups.include?(module_name) count[module_name] = count[module_name] ? count[module_name] + 1 : 0 r[:counter] = count[module_name] end to_return end # TODO(dtan4): change method name... def name_of(dns_name) dns_name.gsub(/\.\z/, "") end def module_name_of(record, counter) normalize_module_name(name_of(record.name.gsub(/\\052/, 'wildcard')) + "-" + record.type + (!counter.nil? ? "-" + counter.to_s : "")) end def zone_id_of(hosted_zone) hosted_zone.id.gsub(%r{\A/hostedzone/}, "") end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_role.rb
lib/terraforming/resource/iam_role.rb
module Terraforming module Resource class IAMRole include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_role") end def tfstate iam_roles.inject({}) do |resources, role| attributes = { "arn" => role.arn, "assume_role_policy" => prettify_policy(role.assume_role_policy_document, breakline: true, unescape: true), "id" => role.role_name, "name" => role.role_name, "path" => role.path, "unique_id" => role.role_id, } resources["aws_iam_role.#{module_name_of(role)}"] = { "type" => "aws_iam_role", "primary" => { "id" => role.role_name, "attributes" => attributes } } resources end end private def iam_roles @client.list_roles.map(&:roles).flatten end def module_name_of(role) normalize_module_name(role.role_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/internet_gateway.rb
lib/terraforming/resource/internet_gateway.rb
module Terraforming module Resource class InternetGateway include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/internet_gateway") end def tfstate internet_gateways.inject({}) do |resources, internet_gateway| next resources if internet_gateway.attachments.empty? attributes = { "id" => internet_gateway.internet_gateway_id, "vpc_id" => internet_gateway.attachments[0].vpc_id, "tags.#" => internet_gateway.tags.length.to_s, } resources["aws_internet_gateway.#{module_name_of(internet_gateway)}"] = { "type" => "aws_internet_gateway", "primary" => { "id" => internet_gateway.internet_gateway_id, "attributes" => attributes } } resources end end private def internet_gateways @client.describe_internet_gateways.map(&:internet_gateways).flatten end def module_name_of(internet_gateway) normalize_module_name(name_from_tag(internet_gateway, internet_gateway.internet_gateway_id)) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/vpc.rb
lib/terraforming/resource/vpc.rb
module Terraforming module Resource class VPC include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/vpc") end def tfstate vpcs.inject({}) do |resources, vpc| attributes = { "cidr_block" => vpc.cidr_block, "enable_dns_hostnames" => enable_dns_hostnames?(vpc).to_s, "enable_dns_support" => enable_dns_support?(vpc).to_s, "id" => vpc.vpc_id, "instance_tenancy" => vpc.instance_tenancy, "tags.#" => vpc.tags.length.to_s, } resources["aws_vpc.#{module_name_of(vpc)}"] = { "type" => "aws_vpc", "primary" => { "id" => vpc.vpc_id, "attributes" => attributes } } resources end end private def enable_dns_hostnames?(vpc) vpc_attribute(vpc, :enableDnsHostnames).enable_dns_hostnames.value end def enable_dns_support?(vpc) vpc_attribute(vpc, :enableDnsSupport).enable_dns_support.value end def module_name_of(vpc) normalize_module_name(name_from_tag(vpc, vpc.vpc_id)) end def vpcs @client.describe_vpcs.map(&:vpcs).flatten end def vpc_attribute(vpc, attribute) @client.describe_vpc_attribute(vpc_id: vpc.vpc_id, attribute: attribute) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/auto_scaling_group.rb
lib/terraforming/resource/auto_scaling_group.rb
module Terraforming module Resource class AutoScalingGroup include Terraforming::Util def self.tf(client: Aws::AutoScaling::Client.new) self.new(client).tf end def self.tfstate(client: Aws::AutoScaling::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/auto_scaling_group") end def tfstate auto_scaling_groups.inject({}) do |resources, group| vpc_zone_specified = vpc_zone_specified?(group) attributes = { "availability_zones.#" => vpc_zone_specified ? "0" : group.availability_zones.length.to_s, "default_cooldown" => "300", "desired_capacity" => group.desired_capacity.to_s, "health_check_grace_period" => group.health_check_grace_period.to_s, "health_check_type" => group.health_check_type, "id" => group.auto_scaling_group_name, "launch_configuration" => group.launch_configuration_name, "load_balancers.#" => "0", "max_size" => group.max_size.to_s, "min_size" => group.min_size.to_s, "name" => group.auto_scaling_group_name, "tag.#" => group.tags.length.to_s, "termination_policies.#" => "0", "vpc_zone_identifier.#" => vpc_zone_specified ? vpc_zone_identifier_of(group).length.to_s : "0", } group.tags.each do |tag| hashcode = tag_hashcode_of(tag) attributes.merge!({ "tag.#{hashcode}.key" => tag.key, "tag.#{hashcode}.propagate_at_launch" => tag.propagate_at_launch.to_s, "tag.#{hashcode}.value" => tag.value, }) end resources["aws_autoscaling_group.#{module_name_of(group)}"] = { "type" => "aws_autoscaling_group", "primary" => { "id" => group.auto_scaling_group_name, "attributes" => attributes, "meta" => { "schema_version" => "1" } } } resources end end private def auto_scaling_groups @client.describe_auto_scaling_groups.map(&:auto_scaling_groups).flatten end def module_name_of(group) normalize_module_name(group.auto_scaling_group_name) end def tag_hashcode_of(tag) Zlib.crc32("#{tag.key}-#{tag.value}-#{tag.propagate_at_launch}-") end def vpc_zone_identifier_of(group) group.vpc_zone_identifier.split(",") end def vpc_zone_specified?(group) group.vpc_zone_identifier && !vpc_zone_identifier_of(group).empty? end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/efs_file_system.rb
lib/terraforming/resource/efs_file_system.rb
module Terraforming module Resource class EFSFileSystem include Terraforming::Util def self.tf(client: Aws::EFS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EFS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/elastic_file_system") end def tfstate file_systems.inject({}) do |resources, efs| attributes = { "creation_token" => efs.creation_token, "id" => efs.file_system_id, "performance_mode" => efs.performance_mode, "tags.%" => "1", "tags.Name" => efs.name, } resources["aws_efs_file_system.#{module_name_of(efs)}"] = { "type" => "aws_efs_file_system", "depends_on" => [], "primary" => { "id" => efs.file_system_id, "attributes" => attributes, "meta" => {}, "tainted" => false, }, "deposed" => [], "provider" => "aws", } resources end end private def file_systems @client.describe_file_systems.data.file_systems.flatten end def module_name_of(efs) normalize_module_name(efs.file_system_id) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/cloud_watch_alarm.rb
lib/terraforming/resource/cloud_watch_alarm.rb
module Terraforming module Resource class CloudWatchAlarm include Terraforming::Util def self.tf(client: Aws::CloudWatch::Client.new) self.new(client).tf end def self.tfstate(client: Aws::CloudWatch::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/cloud_watch_alarm") end def tfstate alarms.inject({}) do |resources, alarm| resources["aws_cloudwatch_metric_alarm.#{module_name_of(alarm)}"] = { "type" => "aws_cloudwatch_metric_alarm", "primary" => { "id" => alarm.alarm_name, "attributes" => alarm_attributes(alarm) } } resources end end private def alarm_attributes(alarm) attributes = { "actions_enabled" => alarm.actions_enabled.to_s, "alarm_description" => sanitize(alarm.alarm_description), "alarm_name" => alarm.alarm_name, "comparison_operator" => alarm.comparison_operator, "evaluation_periods" => alarm.evaluation_periods.to_s, "id" => alarm.alarm_name, "metric_name" => alarm.metric_name, "namespace" => alarm.namespace, "period" => alarm.period.to_s, "statistic" => alarm.statistic, "threshold" => alarm.threshold.to_s, "unit" => sanitize(alarm.unit) } add_checksummed_attributes(attributes, alarm) end def alarms @client.describe_alarms.map(&:metric_alarms).flatten end def module_name_of(alarm) normalize_module_name(alarm.alarm_name) end def sanitize(argument) argument.nil? ? "" : argument end def add_checksummed_attributes(attributes, alarm) %w(insufficient_data_actions alarm_actions ok_actions dimensions).each do |action| attribute = alarm.send(action.to_sym) attributes["#{action}.#"] = attribute.size.to_s attribute.each do |attr| if attr.is_a? String checksum = Zlib.crc32(attr) value = attr else checksum = attr.name value = attr.value end attributes["#{action}.#{checksum}"] = value end end attributes end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/vpn_gateway.rb
lib/terraforming/resource/vpn_gateway.rb
module Terraforming module Resource class VPNGateway include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/vpn_gateway") end def tfstate vpn_gateways.inject({}) do |resources, vpn_gateway| next resources if vpn_gateway.vpc_attachments.empty? attributes = { "id" => vpn_gateway.vpn_gateway_id, "vpc_id" => vpn_gateway.vpc_attachments[0].vpc_id, "availability_zone" => vpn_gateway.availability_zone, "tags.#" => vpn_gateway.tags.length.to_s, } resources["aws_vpn_gateway.#{module_name_of(vpn_gateway)}"] = { "type" => "aws_vpn_gateway", "primary" => { "id" => vpn_gateway.vpn_gateway_id, "attributes" => attributes } } resources end end private def vpn_gateways @client.describe_vpn_gateways.map(&:vpn_gateways).flatten end def module_name_of(vpn_gateway) normalize_module_name(name_from_tag(vpn_gateway, vpn_gateway.vpn_gateway_id)) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/elasti_cache_cluster.rb
lib/terraforming/resource/elasti_cache_cluster.rb
module Terraforming module Resource class ElastiCacheCluster include Terraforming::Util def self.tf(client: Aws::ElastiCache::Client.new) self.new(client).tf end def self.tfstate(client: Aws::ElastiCache::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/elasti_cache_cluster") end def tfstate cache_clusters.inject({}) do |resources, cache_cluster| attributes = { "cache_nodes.#" => cache_cluster.cache_nodes.length.to_s, "cluster_id" => cache_cluster.cache_cluster_id, "engine" => cache_cluster.engine, "engine_version" => cache_cluster.engine_version, "id" => cache_cluster.cache_cluster_id, "node_type" => cache_cluster.cache_node_type, "num_cache_nodes" => "1", "parameter_group_name" => cache_cluster.cache_parameter_group.cache_parameter_group_name, "security_group_ids.#" => security_group_ids_of(cache_cluster).length.to_s, "security_group_names.#" => security_group_names_of(cache_cluster).length.to_s, "subnet_group_name" => cache_cluster.cache_subnet_group_name, "tags.#" => "0", } attributes["port"] = if cache_cluster.configuration_endpoint cache_cluster.configuration_endpoint.port.to_s else cache_cluster.cache_nodes[0].endpoint.port.to_s end if cache_cluster.notification_configuration attributes["notification_topic_arn"] = cache_cluster.notification_configuration.topic_arn end resources["aws_elasticache_cluster.#{module_name_of(cache_cluster)}"] = { "type" => "aws_elasticache_cluster", "primary" => { "id" => cache_cluster.cache_cluster_id, "attributes" => attributes } } resources end end private def cache_clusters @client.describe_cache_clusters(show_cache_node_info: true).map(&:cache_clusters).flatten end def cluster_in_vpc?(cache_cluster) cache_cluster.cache_security_groups.empty? end def security_group_ids_of(cache_cluster) cache_cluster.security_groups.map { |sg| sg.security_group_id } end def security_group_names_of(cache_cluster) cache_cluster.cache_security_groups.map { |sg| sg.cache_security_group_name } end def module_name_of(cache_cluster) normalize_module_name(cache_cluster.cache_cluster_id) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_policy.rb
lib/terraforming/resource/iam_policy.rb
module Terraforming module Resource class IAMPolicy include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_policy") end def tfstate iam_policies.inject({}) do |resources, policy| version = iam_policy_version_of(policy) attributes = { "id" => policy.arn, "name" => policy.policy_name, "path" => policy.path, "description" => iam_policy_description(policy), "policy" => prettify_policy(version.document, breakline: true, unescape: true), } resources["aws_iam_policy.#{module_name_of(policy)}"] = { "type" => "aws_iam_policy", "primary" => { "id" => policy.arn, "attributes" => attributes } } resources end end private def iam_policies @client.list_policies(scope: "Local").map(&:policies).flatten end def iam_policy_description(policy) @client.get_policy(policy_arn: policy.arn).policy.description end def iam_policy_version_of(policy) @client.get_policy_version(policy_arn: policy.arn, version_id: policy.default_version_id).policy_version end def module_name_of(policy) normalize_module_name(policy.policy_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_policy_attachment.rb
lib/terraforming/resource/iam_policy_attachment.rb
module Terraforming module Resource class IAMPolicyAttachment include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_policy_attachment") end def tfstate iam_policy_attachments.inject({}) do |resources, policy_attachment| attributes = { "id" => policy_attachment[:name], "name" => policy_attachment[:name], "policy_arn" => policy_attachment[:arn], "groups.#" => policy_attachment[:entities].policy_groups.length.to_s, "users.#" => policy_attachment[:entities].policy_users.length.to_s, "roles.#" => policy_attachment[:entities].policy_roles.length.to_s, } resources["aws_iam_policy_attachment.#{module_name_of(policy_attachment)}"] = { "type" => "aws_iam_policy_attachment", "primary" => { "id" => policy_attachment[:name], "attributes" => attributes } } resources end end private def attachment_name_from(policy) "#{policy.policy_name}-policy-attachment" end def entities_for_policy(policy) # list_entities_for_policy is a weird one: the response class # has three different member variables that we need to # paginate through altogether. result = Aws::IAM::Types::ListEntitiesForPolicyResponse.new result.policy_groups = [] result.policy_users = [] result.policy_roles = [] @client.list_entities_for_policy(policy_arn: policy.arn).each do |resp| result.policy_groups += resp.policy_groups result.policy_users += resp.policy_users result.policy_roles += resp.policy_roles end result end def iam_policies @client.list_policies(scope: "All", only_attached: true).map(&:policies).flatten end def iam_policy_attachments iam_policies.map do |policy| { arn: policy.arn, entities: entities_for_policy(policy), name: attachment_name_from(policy), } end end def module_name_of(policy_attachment) normalize_module_name(policy_attachment[:name]) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/network_interface.rb
lib/terraforming/resource/network_interface.rb
module Terraforming module Resource class NetworkInterface include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/network_interface") end def tfstate network_interfaces.inject({}) do |resources, network_interface| attributes = { "attachment.#" => attachment_of(network_interface) ? "1" : "0", "id" => network_interface.network_interface_id, "private_ips.#" => private_ips_of(network_interface).length.to_s, "security_groups.#" => security_groups_of(network_interface).length.to_s, "source_dest_check" => network_interface.source_dest_check.to_s, "subnet_id" => network_interface.subnet_id, "tags.#" => network_interface.tag_set.length.to_s, } resources["aws_network_interface.#{module_name_of(network_interface)}"] = { "type" => "aws_network_interface", "primary" => { "id" => network_interface.network_interface_id, "attributes" => attributes } } resources end end private def attachment_of(network_interface) network_interface.attachment end def private_ips_of(network_interface) network_interface.private_ip_addresses.map { |addr| addr.private_ip_address } end def security_groups_of(network_interface) network_interface.groups.map { |group| group.group_id } end def module_name_of(network_interface) network_interface.network_interface_id end def network_interfaces @client.describe_network_interfaces.map(&:network_interfaces).flatten end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/db_subnet_group.rb
lib/terraforming/resource/db_subnet_group.rb
module Terraforming module Resource class DBSubnetGroup include Terraforming::Util def self.tf(client: Aws::RDS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::RDS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/db_subnet_group") end def tfstate db_subnet_groups.inject({}) do |resources, subnet_group| attributes = { "description" => subnet_group.db_subnet_group_description, "name" => subnet_group.db_subnet_group_name, "subnet_ids.#" => subnet_group.subnets.length.to_s } resources["aws_db_subnet_group.#{module_name_of(subnet_group)}"] = { "type" => "aws_db_subnet_group", "primary" => { "id" => subnet_group.db_subnet_group_name, "attributes" => attributes } } resources end end private def db_subnet_groups @client.describe_db_subnet_groups.map(&:db_subnet_groups).flatten end def module_name_of(subnet_group) normalize_module_name(subnet_group.db_subnet_group_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_role_policy.rb
lib/terraforming/resource/iam_role_policy.rb
module Terraforming module Resource class IAMRolePolicy include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_role_policy") end def tfstate iam_role_policies.inject({}) do |resources, policy| attributes = { "id" => iam_role_policy_id_of(policy), "name" => policy.policy_name, "policy" => prettify_policy(policy.policy_document, breakline: true, unescape: true), "role" => policy.role_name, } resources["aws_iam_role_policy.#{unique_name(policy)}"] = { "type" => "aws_iam_role_policy", "primary" => { "id" => iam_role_policy_id_of(policy), "attributes" => attributes } } resources end end private def unique_name(policy) "#{normalize_module_name(policy.role_name)}_#{normalize_module_name(policy.policy_name)}" end def iam_role_policy_id_of(policy) "#{policy.role_name}:#{policy.policy_name}" end def iam_roles @client.list_roles.map(&:roles).flatten end def iam_role_policy_names_in(role) @client.list_role_policies(role_name: role.role_name).policy_names end def iam_role_policy_of(role, policy_name) @client.get_role_policy(role_name: role.role_name, policy_name: policy_name) end def iam_role_policies iam_roles.map do |role| iam_role_policy_names_in(role).map { |policy_name| iam_role_policy_of(role, policy_name) } end.flatten end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/security_group.rb
lib/terraforming/resource/security_group.rb
module Terraforming module Resource class SecurityGroup include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/security_group") end def tfstate security_groups.inject({}) do |resources, security_group| attributes = { "description" => security_group.description, "id" => security_group.group_id, "name" => security_group.group_name, "owner_id" => security_group.owner_id, "vpc_id" => security_group.vpc_id || "", } attributes.merge!(tags_attributes_of(security_group)) attributes.merge!(egress_attributes_of(security_group)) attributes.merge!(ingress_attributes_of(security_group)) resources["aws_security_group.#{module_name_of(security_group)}"] = { "type" => "aws_security_group", "primary" => { "id" => security_group.group_id, "attributes" => attributes } } resources end end private def ingress_attributes_of(security_group) ingresses = dedup_permissions(security_group.ip_permissions, security_group.group_id) attributes = { "ingress.#" => ingresses.length.to_s } ingresses.each do |permission| attributes.merge!(permission_attributes_of(security_group, permission, "ingress")) end attributes end def egress_attributes_of(security_group) egresses = dedup_permissions(security_group.ip_permissions_egress, security_group.group_id) attributes = { "egress.#" => egresses.length.to_s } egresses.each do |permission| attributes.merge!(permission_attributes_of(security_group, permission, "egress")) end attributes end def group_hashcode_of(group) Zlib.crc32(group) end def module_name_of(security_group) if security_group.vpc_id.nil? normalize_module_name(security_group.group_name.to_s) else normalize_module_name("#{security_group.vpc_id}-#{security_group.group_name}") end end def permission_attributes_of(security_group, permission, type) hashcode = permission_hashcode_of(security_group, permission) security_groups = security_groups_in(permission, security_group).reject do |identifier| [security_group.group_name, security_group.group_id].include?(identifier) end attributes = { "#{type}.#{hashcode}.from_port" => (permission.from_port || 0).to_s, "#{type}.#{hashcode}.to_port" => (permission.to_port || 0).to_s, "#{type}.#{hashcode}.protocol" => permission.ip_protocol, "#{type}.#{hashcode}.cidr_blocks.#" => permission.ip_ranges.length.to_s, "#{type}.#{hashcode}.ipv6_cidr_blocks.#" => permission.ipv_6_ranges.length.to_s, "#{type}.#{hashcode}.prefix_list_ids.#" => permission.prefix_list_ids.length.to_s, "#{type}.#{hashcode}.security_groups.#" => security_groups.length.to_s, "#{type}.#{hashcode}.self" => self_referenced_permission?(security_group, permission).to_s, } permission.ip_ranges.each_with_index do |range, index| attributes["#{type}.#{hashcode}.cidr_blocks.#{index}"] = range.cidr_ip end permission.ipv_6_ranges.each_with_index do |range, index| attributes["#{type}.#{hashcode}.ipv6_cidr_blocks.#{index}"] = range.cidr_ipv_6 end permission.prefix_list_ids.each_with_index do |prefix_list, index| attributes["#{type}.#{hashcode}.prefix_list_ids.#{index}"] = prefix_list.prefix_list_id end security_groups.each do |group| attributes["#{type}.#{hashcode}.security_groups.#{group_hashcode_of(group)}"] = group end attributes end def dedup_permissions(permissions, group_id) group_permissions(permissions).inject([]) do |result, (_, perms)| group_ids = perms.map(&:user_id_group_pairs).flatten.map(&:group_id) if group_ids.length == 1 && group_ids.first == group_id result << merge_permissions(perms) else result.concat(perms) end result end end def group_permissions(permissions) permissions.group_by { |permission| [permission.ip_protocol, permission.to_port, permission.from_port] } end def merge_permissions(permissions) master_permission = permissions.pop permissions.each do |permission| master_permission.user_id_group_pairs.concat(permission.user_id_group_pairs) master_permission.ip_ranges.concat(permission.ip_ranges) master_permission.ipv_6_ranges.concat(permission.ipv_6_ranges) end master_permission end def permission_hashcode_of(security_group, permission) string = "#{permission.from_port || 0}-" << "#{permission.to_port || 0}-" << "#{permission.ip_protocol}-" << "#{self_referenced_permission?(security_group, permission)}-" permission.ip_ranges.each { |range| string << "#{range.cidr_ip}-" } permission.ipv_6_ranges.each { |range| string << "#{range.cidr_ipv_6}-" } security_groups_in(permission, security_group).each { |group| string << "#{group}-" } Zlib.crc32(string) end def self_referenced_permission?(security_group, permission) (security_groups_in(permission, security_group) & [security_group.group_id, security_group.group_name]).any? end def security_groups @client.describe_security_groups.map(&:security_groups).flatten end def security_groups_in(permission, security_group) permission.user_id_group_pairs.map do |range| # EC2-Classic, same account if security_group.owner_id == range.user_id && !range.group_name.nil? range.group_name # VPC elsif security_group.owner_id == range.user_id && range.group_name.nil? range.group_id # EC2-Classic, other account else "#{range.user_id}/#{range.group_name || range.group_id}" end end end def tags_attributes_of(security_group) tags = security_group.tags attributes = { "tags.#" => tags.length.to_s } tags.each { |tag| attributes["tags.#{tag.key}"] = tag.value } attributes end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/route_table_association.rb
lib/terraforming/resource/route_table_association.rb
module Terraforming module Resource class RouteTableAssociation include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/route_table_association") end def tfstate resources = {} route_tables.each do |route_table| associations_of(route_table).each do |assoc| attributes = { "id" => assoc.route_table_association_id, "route_table_id" => assoc.route_table_id, "subnet_id" => assoc.subnet_id, } resources["aws_route_table_association.#{module_name_of(route_table, assoc)}"] = { "type" => "aws_route_table_association", "primary" => { "id" => assoc.route_table_association_id, "attributes" => attributes } } end end resources end private def associations_of(route_table) route_table.associations.reject { |association| association.subnet_id.nil? } end def module_name_of(route_table, assoc) normalize_module_name(name_from_tag(route_table, route_table.route_table_id) + '-' + assoc.route_table_association_id) end def route_tables @client.describe_route_tables.map(&:route_tables).flatten end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/kms_key.rb
lib/terraforming/resource/kms_key.rb
module Terraforming module Resource class KMSKey include Terraforming::Util def self.tf(client: Aws::KMS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::KMS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/kms_key") end def tfstate keys.inject({}) do |resources, key| resources["aws_kms_key.#{module_name_of(key)}"] = { "type" => "aws_kms_key", "primary" => { "id" => key.key_id, "attributes" => { "arn" => key.arn, "description" => key.description, "enable_key_rotation" => key_rotation_status_of(key).key_rotation_enabled.to_s, "id" => key.key_id, "is_enabled" => key.enabled.to_s, "key_id" => key.key_id, "key_usage" => key.key_usage, "policy" => key_policy_of(key), }, }, } resources end end private def aliases @aliases ||= @client.list_aliases.aliases end def keys @client .list_keys .keys .reject { |key| managed_master_key?(key) } .map { |key| @client.describe_key(key_id: key.key_id) } .map(&:key_metadata) .reject { |metadata| metadata.origin == "EXTERNAL" } # external origin key is not supoprted by Terraform end def key_policy_of(key) policies = @client.list_key_policies(key_id: key.key_id).policy_names return "" if policies.empty? @client.get_key_policy(key_id: key.key_id, policy_name: policies[0]).policy end def key_rotation_status_of(key) @client.get_key_rotation_status(key_id: key.key_id) end def managed_master_key?(key) !aliases.select { |a| a.target_key_id == key.key_id && a.alias_name =~ %r{\Aalias/aws/} }.empty? end def module_name_of(key) normalize_module_name(key.key_id) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/redshift.rb
lib/terraforming/resource/redshift.rb
module Terraforming module Resource class Redshift include Terraforming::Util def self.tf(client: Aws::Redshift::Client.new) self.new(client).tf end def self.tfstate(client: Aws::Redshift::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/redshift") end def tfstate clusters.inject({}) do |resources, cluster| attributes = { "cluster_identifier" => cluster.cluster_identifier, "cluster_type" => cluster.number_of_nodes == 1 ? "single-node" : "multi-node", "node_type" => cluster.node_type, "master_password" => "xxxxxxxx", "master_username" => cluster.master_username, "availability_zone" => cluster.availability_zone, "preferred_maintenance_window" => cluster.preferred_maintenance_window, "cluster_parameter_group_name" => cluster.cluster_parameter_groups[0].parameter_group_name, "automated_snapshot_retention_period" => cluster.automated_snapshot_retention_period.to_s, "port" => cluster.endpoint.port.to_s, "cluster_version" => cluster.cluster_version, "allow_version_upgrade" => cluster.allow_version_upgrade.to_s, "number_of_nodes" => cluster.number_of_nodes.to_s, "publicly_accessible" => cluster.publicly_accessible.to_s, "encrypted" => cluster.encrypted.to_s, "skip_final_snapshot" => "true", } attributes["database_name"] = cluster.db_name if cluster.db_name resources["aws_redshift_cluster.#{module_name_of(cluster)}"] = { "type" => "aws_redshift_cluster", "primary" => { "id" => cluster.cluster_identifier, "attributes" => attributes } } resources end end private def clusters @client.describe_clusters.map(&:clusters).flatten end def module_name_of(cluster) normalize_module_name(cluster.cluster_identifier) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/sns_topic_subscription.rb
lib/terraforming/resource/sns_topic_subscription.rb
module Terraforming module Resource class SNSTopicSubscription include Terraforming::Util def self.tf(client: Aws::SNS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::SNS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/sns_topic_subscription") end def tfstate subscriptions.reject { |x| x["Protocol"].include?("email") } .inject({}) do |resources, subscription| attributes = { "id" => subscription["SubscriptionArn"], "topic_arn" => subscription["TopicArn"], "protocol" => subscription["Protocol"], "endpoint" => subscription["Endpoint"], "raw_message_delivery" => subscription.key?("RawMessageDelivery") ? subscription["RawMessageDelivery"] : "false", "confirmation_timeout_in_minutes" => subscription.key?("ConfirmationTimeoutInMinutes") ? subscription["ConfirmationTimeoutInMinutes"] : "1", "endpoint_auto_confirms" => subscription.key?("EndpointAutoConfirms") ? subscription["EndpointAutoConfirms"] : "false" } resources["aws_sns_topic_subscription.#{module_name_of(subscription)}"] = { "type" => "aws_sns_topic_subscription", "primary" => { "id" => subscription["SubscriptionArn"], "attributes" => attributes } } resources end end private def subscriptions subscription_arns.map do |subscription_arn| # check explicitly for an issue with some subscriptions that returns ARN=PendingConfirmation next if subscription_arn == "PendingConfirmation" attributes = @client.get_subscription_attributes({ subscription_arn: subscription_arn, }).attributes attributes["SubscriptionArn"] = subscription_arn attributes end.compact end def subscription_arns token = "" arns = [] loop do resp = @client.list_subscriptions(next_token: token) arns += resp.subscriptions.map(&:subscription_arn).flatten token = resp.next_token break if token.nil? end arns end def module_name_of(subscription) normalize_module_name(subscription["SubscriptionArn"].split(":").last) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_user_policy.rb
lib/terraforming/resource/iam_user_policy.rb
module Terraforming module Resource class IAMUserPolicy include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_user_policy") end def tfstate iam_user_policies.inject({}) do |resources, policy| attributes = { "id" => iam_user_policy_id_of(policy), "name" => policy.policy_name, "policy" => prettify_policy(policy.policy_document, breakline: true, unescape: true), "user" => policy.user_name, } resources["aws_iam_user_policy.#{unique_name(policy)}"] = { "type" => "aws_iam_user_policy", "primary" => { "id" => iam_user_policy_id_of(policy), "attributes" => attributes } } resources end end private def unique_name(policy) "#{normalize_module_name(policy.user_name)}_#{normalize_module_name(policy.policy_name)}" end def iam_user_policy_id_of(policy) "#{policy.user_name}:#{policy.policy_name}" end def iam_users @client.list_users.map(&:users).flatten end def iam_user_policy_names_in(user) @client.list_user_policies(user_name: user.user_name).policy_names end def iam_user_policy_of(user, policy_name) @client.get_user_policy(user_name: user.user_name, policy_name: policy_name) end def iam_user_policies iam_users.map do |user| iam_user_policy_names_in(user).map { |policy_name| iam_user_policy_of(user, policy_name) } end.flatten end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/elasti_cache_subnet_group.rb
lib/terraforming/resource/elasti_cache_subnet_group.rb
module Terraforming module Resource class ElastiCacheSubnetGroup include Terraforming::Util def self.tf(client: Aws::ElastiCache::Client.new) self.new(client).tf end def self.tfstate(client: Aws::ElastiCache::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/elasti_cache_subnet_group") end def tfstate cache_subnet_groups.inject({}) do |resources, cache_subnet_group| attributes = { "description" => cache_subnet_group.cache_subnet_group_description, "name" => cache_subnet_group.cache_subnet_group_name, "subnet_ids.#" => subnet_ids_of(cache_subnet_group).length.to_s, } resources["aws_elasticache_subnet_group.#{module_name_of(cache_subnet_group)}"] = { "type" => "aws_elasticache_subnet_group", "primary" => { "id" => cache_subnet_group.cache_subnet_group_name, "attributes" => attributes } } resources end end private def cache_subnet_groups @client.describe_cache_subnet_groups.map(&:cache_subnet_groups).flatten end def subnet_ids_of(cache_subnet_group) cache_subnet_group.subnets.map { |sn| sn.subnet_identifier } end def module_name_of(cache_subnet_group) normalize_module_name(cache_subnet_group.cache_subnet_group_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_user.rb
lib/terraforming/resource/iam_user.rb
module Terraforming module Resource class IAMUser include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_user") end def tfstate iam_users.inject({}) do |resources, user| attributes = { "arn" => user.arn, "id" => user.user_name, "name" => user.user_name, "path" => user.path, "unique_id" => user.user_id, "force_destroy" => "false", } resources["aws_iam_user.#{module_name_of(user)}"] = { "type" => "aws_iam_user", "primary" => { "id" => user.user_name, "attributes" => attributes, } } resources end end private def iam_users @client.list_users.map(&:users).flatten end def module_name_of(user) normalize_module_name(user.user_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/rds.rb
lib/terraforming/resource/rds.rb
module Terraforming module Resource class RDS include Terraforming::Util def self.tf(client: Aws::RDS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::RDS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/rds") end def tfstate db_instances.inject({}) do |resources, instance| attributes = { "address" => instance.endpoint.address, "allocated_storage" => instance.allocated_storage.to_s, "availability_zone" => instance.availability_zone, "backup_retention_period" => instance.backup_retention_period.to_s, "backup_window" => instance.preferred_backup_window, "db_subnet_group_name" => instance.db_subnet_group ? instance.db_subnet_group.db_subnet_group_name : "", "endpoint" => instance.endpoint.address, "engine" => instance.engine, "engine_version" => instance.engine_version, "final_snapshot_identifier" => "#{instance.db_instance_identifier}-final", "id" => instance.db_instance_identifier, "identifier" => instance.db_instance_identifier, "instance_class" => instance.db_instance_class, "maintenance_window" => instance.preferred_maintenance_window, "multi_az" => instance.multi_az.to_s, "name" => instance.db_name, "parameter_group_name" => instance.db_parameter_groups[0].db_parameter_group_name, "password" => "xxxxxxxx", "port" => instance.endpoint.port.to_s, "publicly_accessible" => instance.publicly_accessible.to_s, "security_group_names.#" => instance.db_security_groups.length.to_s, "status" => instance.db_instance_status, "storage_type" => instance.storage_type, "username" => instance.master_username, "vpc_security_group_ids.#" => instance.vpc_security_groups.length.to_s, } resources["aws_db_instance.#{module_name_of(instance)}"] = { "type" => "aws_db_instance", "primary" => { "id" => instance.db_instance_identifier, "attributes" => attributes } } resources end end private def db_instances @client.describe_db_instances.map(&:db_instances).flatten end def module_name_of(instance) normalize_module_name(instance.db_instance_identifier) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/launch_configuration.rb
lib/terraforming/resource/launch_configuration.rb
module Terraforming module Resource class LaunchConfiguration include Terraforming::Util def self.tf(client: Aws::AutoScaling::Client.new) self.new(client).tf end def self.tfstate(client: Aws::AutoScaling::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/launch_configuration") end def tfstate launch_configurations.inject({}) do |resources, lc| attributes = { "name" => lc.launch_configuration_name, "image_id" => lc.image_id, "instance_type" => lc.instance_type, "key_name" => lc.key_name, "security_groups.#" => lc.security_groups.length.to_s, "associate_public_ip_address" => lc.associate_public_ip_address.to_s, "user_data" => lc.user_data, "enable_monitoring" => lc.instance_monitoring.enabled.to_s, "ebs_optimized" => lc.ebs_optimized.to_s, "root_block_device.#" => root_block_device_count(lc).to_s, "ebs_block_device.#" => ebs_block_device_count(lc).to_s, "ephemeral_block_device.#" => ephemeral_block_device_count(lc).to_s } lc.security_groups.each do |sg| hash = hash_security_group(sg) attributes["security_groups.#{hash}"] = sg end attributes["iam_instance_profile"] = lc.iam_instance_profile if lc.iam_instance_profile attributes["spot_price"] = lc.spot_price if lc.spot_price attributes["placement_tenancy"] = lc.placement_tenancy if lc.placement_tenancy resources["aws_launch_configuration.#{module_name_of(lc)}"] = { "type" => "aws_launch_configuration", "primary" => { "id" => lc.launch_configuration_name, "attributes" => attributes } } resources end end private # Taken from http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html def root_block_device?(block_device) %w(/dev/sda1 /dev/xvda).include? block_device.device_name end def root_block_device_count(launch_configuration) launch_configuration.block_device_mappings.select do |volume| root_block_device?(volume) end.length end def ebs_block_device?(block_device) block_device.virtual_name.nil? && block_device.ebs end def ebs_block_device_count(launch_configuration) launch_configuration.block_device_mappings.select do |volume| ebs_block_device?(volume) && !root_block_device?(volume) end.length end def ephemeral_block_device?(block_device) block_device.virtual_name != nil end def ephemeral_block_device_count(launch_configuration) launch_configuration.block_device_mappings.select do |volume| ephemeral_block_device?(volume) end.length end def hash_security_group(name) Zlib.crc32(name) end def launch_configurations @client.describe_launch_configurations.map(&:launch_configurations).flatten end def module_name_of(launch_configuration) normalize_module_name(launch_configuration.launch_configuration_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/s3.rb
lib/terraforming/resource/s3.rb
module Terraforming module Resource class S3 include Terraforming::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
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/db_security_group.rb
lib/terraforming/resource/db_security_group.rb
module Terraforming module Resource class DBSecurityGroup include Terraforming::Util def self.tf(client: Aws::RDS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::RDS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/db_security_group") end def tfstate db_security_groups.inject({}) do |resources, security_group| attributes = { "db_subnet_group_name" => security_group.db_security_group_name, "id" => security_group.db_security_group_name, "ingress.#" => ingresses_of(security_group).length.to_s, "name" => security_group.db_security_group_name, } resources["aws_db_security_group.#{module_name_of(security_group)}"] = { "type" => "aws_db_security_group", "primary" => { "id" => security_group.db_security_group_name, "attributes" => attributes } } resources end end private def ingresses_of(security_group) security_group.ec2_security_groups + security_group.ip_ranges end def db_security_groups @client.describe_db_security_groups.map(&:db_security_groups).flatten.select { |sg| !ingresses_of(sg).empty? } end def module_name_of(security_group) normalize_module_name(security_group.db_security_group_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/ec2.rb
lib/terraforming/resource/ec2.rb
module Terraforming module Resource class EC2 include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/ec2") end def tfstate instances.inject({}) do |resources, instance| in_vpc = in_vpc?(instance) block_devices = block_devices_of(instance) attributes = { "ami" => instance.image_id, "associate_public_ip_address" => associate_public_ip?(instance).to_s, "availability_zone" => instance.placement.availability_zone, "ebs_block_device.#" => ebs_block_devices_in(block_devices, instance).length.to_s, "ebs_optimized" => instance.ebs_optimized.to_s, "ephemeral_block_device.#" => "0", # Terraform 0.6.1 cannot fetch this field from AWS "id" => instance.instance_id, "instance_type" => instance.instance_type, "monitoring" => monitoring_state(instance).to_s, "private_dns" => instance.private_dns_name, "private_ip" => instance.private_ip_address, "public_dns" => instance.public_dns_name, "public_ip" => instance.public_ip_address, "root_block_device.#" => root_block_devices_in(block_devices, instance).length.to_s, "security_groups.#" => in_vpc ? "0" : instance.security_groups.length.to_s, "source_dest_check" => instance.source_dest_check.to_s, "tenancy" => instance.placement.tenancy, "vpc_security_group_ids.#" => in_vpc ? instance.security_groups.length.to_s : "0", } placement_group = instance.placement.group_name attributes["placement_group"] = placement_group unless placement_group.empty? attributes["subnet_id"] = instance.subnet_id if in_vpc?(instance) resources["aws_instance.#{module_name_of(instance)}"] = { "type" => "aws_instance", "primary" => { "id" => instance.instance_id, "attributes" => attributes, "meta" => { "schema_version" => "1" } } } resources end end private def block_device_ids_of(instance) instance.block_device_mappings.map { |bdm| bdm.ebs.volume_id } end def block_devices_of(instance) return [] if instance.block_device_mappings.empty? @client.describe_volumes(volume_ids: block_device_ids_of(instance)).map(&:volumes).flatten end def block_device_mapping_of(instance, volume_id) instance.block_device_mappings.select { |bdm| bdm.ebs.volume_id == volume_id }[0] end def ebs_block_devices_in(block_devices, instance) block_devices.reject do |bd| root_block_device?(block_device_mapping_of(instance, bd.volume_id), instance) end end # # NOTE(dtan4): # Original logic is here: # https://github.com/hashicorp/terraform/blob/281e4d3e67f66daab9cdb1f7c8b6f602d949e5ee/builtin/providers/aws/resource_aws_instance.go#L481-L501 # def in_vpc?(instance) !vpc_security_groups_of(instance).empty? || (instance.subnet_id && instance.subnet_id != "" && instance.security_groups.empty?) end def associate_public_ip?(instance) !instance.public_ip_address.to_s.empty? end def monitoring_state(instance) %w(enabled pending).include?(instance.monitoring.state) end def instances @client.describe_instances.map(&:reservations).flatten.map(&:instances).flatten.reject do |instance| instance.state.name == "terminated" end end def module_name_of(instance) normalize_module_name(name_from_tag(instance, instance.instance_id)) end def root_block_device?(block_device_mapping, instance) block_device_mapping.device_name == instance.root_device_name end def root_block_devices_in(block_devices, instance) block_devices.select { |bd| root_block_device?(block_device_mapping_of(instance, bd.volume_id), instance) } end def vpc_security_groups_of(instance) instance.security_groups.select { |security_group| /\Asg-/ =~ security_group.group_id } end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/eip.rb
lib/terraforming/resource/eip.rb
module Terraforming module Resource class EIP include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/eip") end def tfstate eips.inject({}) do |resources, addr| attributes = { "association_id" => addr.association_id, "domain" => addr.domain, "id" => vpc?(addr) ? addr.allocation_id : addr.public_ip, "instance" => addr.instance_id, "network_interface" => addr.network_interface_id, "private_ip" => addr.private_ip_address, "public_ip" => addr.public_ip, "vpc" => vpc?(addr).to_s, } attributes.delete_if { |_k, v| v.nil? } resources["aws_eip.#{module_name_of(addr)}"] = { "type" => "aws_eip", "primary" => { "id" => vpc?(addr) ? addr.allocation_id : addr.public_ip, "attributes" => attributes } } resources end end private def eips @client.describe_addresses.map(&:addresses).flatten end def vpc?(addr) addr.domain.eql?("vpc") end def module_name_of(addr) if vpc?(addr) normalize_module_name(addr.allocation_id) else normalize_module_name(addr.public_ip) end end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/elb.rb
lib/terraforming/resource/elb.rb
module Terraforming module Resource class ELB include Terraforming::Util def self.tf(client: Aws::ElasticLoadBalancing::Client.new) self.new(client).tf end def self.tfstate(client: Aws::ElasticLoadBalancing::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/elb") end def tfstate load_balancers.inject({}) do |resources, load_balancer| load_balancer_attributes = load_balancer_attributes_of(load_balancer) attributes = { "availability_zones.#" => load_balancer.availability_zones.length.to_s, "connection_draining" => load_balancer_attributes.connection_draining.enabled.to_s, "connection_draining_timeout" => load_balancer_attributes.connection_draining.timeout.to_s, "cross_zone_load_balancing" => load_balancer_attributes.cross_zone_load_balancing.enabled.to_s, "dns_name" => load_balancer.dns_name, "id" => load_balancer.load_balancer_name, "idle_timeout" => load_balancer_attributes.connection_settings.idle_timeout.to_s, "instances.#" => load_balancer.instances.length.to_s, "internal" => internal?(load_balancer).to_s, "name" => load_balancer.load_balancer_name, "source_security_group" => load_balancer.source_security_group.group_name, } if load_balancer_attributes.access_log.enabled end attributes.merge!(access_logs_attributes_of(load_balancer_attributes)) attributes.merge!(healthcheck_attributes_of(load_balancer)) attributes.merge!(listeners_attributes_of(load_balancer)) attributes.merge!(sg_attributes_of(load_balancer)) attributes.merge!(subnets_attributes_of(load_balancer)) attributes.merge!(instances_attributes_of(load_balancer)) attributes.merge!(tags_attributes_of(load_balancer)) resources["aws_elb.#{module_name_of(load_balancer)}"] = { "type" => "aws_elb", "primary" => { "id" => load_balancer.load_balancer_name, "attributes" => attributes } } resources end end def access_logs_attributes_of(load_balancer_attributes) access_log = load_balancer_attributes.access_log if access_log.enabled { "access_logs.#" => "1", "access_logs.0.bucket" => access_log.s3_bucket_name, "access_logs.0.bucket_prefix" => access_log.s3_bucket_prefix, "access_logs.0.interval" => access_log.emit_interval.to_s, } else { "access_logs.#" => "0", } end end def healthcheck_attributes_of(elb) hashcode = healthcheck_hashcode_of(elb.health_check) attributes = { # Now each ELB supports one heatlhcheck "health_check.#" => "1", "health_check.#{hashcode}.healthy_threshold" => elb.health_check.healthy_threshold.to_s, "health_check.#{hashcode}.interval" => elb.health_check.interval.to_s, "health_check.#{hashcode}.target" => elb.health_check.target, "health_check.#{hashcode}.timeout" => elb.health_check.timeout.to_s, "health_check.#{hashcode}.unhealthy_threshold" => elb.health_check.unhealthy_threshold.to_s } attributes end def healthcheck_hashcode_of(health_check) string = "#{health_check.healthy_threshold}-" << "#{health_check.unhealthy_threshold}-" << "#{health_check.target}-" << "#{health_check.interval}-" << "#{health_check.timeout}-" Zlib.crc32(string) end def tags_attributes_of(elb) tags = @client.describe_tags(load_balancer_names: [elb.load_balancer_name]).tag_descriptions.first.tags attributes = { "tags.#" => tags.length.to_s } tags.each do |tag| attributes["tags.#{tag.key}"] = tag.value end attributes end def instances_attributes_of(elb) attributes = { "instances.#" => elb.instances.length.to_s } elb.instances.each do |instance| attributes["instances.#{Zlib.crc32(instance.instance_id)}"] = instance.instance_id end attributes end def subnets_attributes_of(elb) attributes = { "subnets.#" => elb.subnets.length.to_s } elb.subnets.each do |subnet_id| attributes["subnets.#{Zlib.crc32(subnet_id)}"] = subnet_id end attributes end def sg_attributes_of(elb) attributes = { "security_groups.#" => elb.security_groups.length.to_s } elb.security_groups.each do |sg_id| attributes["security_groups.#{Zlib.crc32(sg_id)}"] = sg_id end attributes end def listeners_attributes_of(elb) attributes = { "listener.#" => elb.listener_descriptions.length.to_s } elb.listener_descriptions.each do |listener_description| attributes.merge!(listener_attributes_of(listener_description.listener)) end attributes end def listener_attributes_of(listener) hashcode = listener_hashcode_of(listener) attributes = { "listener.#{hashcode}.instance_port" => listener.instance_port.to_s, "listener.#{hashcode}.instance_protocol" => listener.instance_protocol.downcase, "listener.#{hashcode}.lb_port" => listener.load_balancer_port.to_s, "listener.#{hashcode}.lb_protocol" => listener.protocol.downcase, "listener.#{hashcode}.ssl_certificate_id" => listener.ssl_certificate_id } attributes end def listener_hashcode_of(listener) string = "#{listener.instance_port}-" << "#{listener.instance_protocol.downcase}-" << "#{listener.load_balancer_port}-" << "#{listener.protocol.downcase}-" << "#{listener.ssl_certificate_id}-" Zlib.crc32(string) end def load_balancers @client.describe_load_balancers.map(&:load_balancer_descriptions).flatten end def load_balancer_attributes_of(load_balancer) @client.describe_load_balancer_attributes(load_balancer_name: load_balancer.load_balancer_name).load_balancer_attributes end def module_name_of(load_balancer) normalize_module_name(load_balancer.load_balancer_name) end def vpc_elb?(load_balancer) load_balancer.vpc_id != "" end def internal?(load_balancer) load_balancer.scheme == "internal" end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_group_policy.rb
lib/terraforming/resource/iam_group_policy.rb
module Terraforming module Resource class IAMGroupPolicy include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_group_policy") end def tfstate iam_group_policies.inject({}) do |resources, policy| attributes = { "group" => policy.group_name, "id" => iam_group_policy_id_of(policy), "name" => policy.policy_name, "policy" => prettify_policy(policy.policy_document, breakline: true, unescape: true) } resources["aws_iam_group_policy.#{unique_name(policy)}"] = { "type" => "aws_iam_group_policy", "primary" => { "id" => iam_group_policy_id_of(policy), "attributes" => attributes } } resources end end private def unique_name(policy) "#{normalize_module_name(policy.group_name)}_#{normalize_module_name(policy.policy_name)}" end def iam_group_policy_id_of(policy) "#{policy.group_name}:#{policy.policy_name}" end def iam_groups @client.list_groups.map(&:groups).flatten end def iam_group_policy_names_in(group) @client.list_group_policies(group_name: group.group_name).policy_names end def iam_group_policy_of(group, policy_name) @client.get_group_policy(group_name: group.group_name, policy_name: policy_name) end def iam_group_policies iam_groups.map do |group| iam_group_policy_names_in(group).map { |policy_name| iam_group_policy_of(group, policy_name) } end.flatten end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/route_table.rb
lib/terraforming/resource/route_table.rb
module Terraforming module Resource class RouteTable include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/route_table") end def tfstate route_tables.inject({}) do |resources, route_table| attributes = { "id" => route_table.route_table_id, "vpc_id" => route_table.vpc_id, } attributes.merge!(tags_attributes_of(route_table)) attributes.merge!(routes_attributes_of(route_table)) attributes.merge!(propagating_vgws_attributes_of(route_table)) resources["aws_route_table.#{module_name_of(route_table)}"] = { "type" => "aws_route_table", "primary" => { "id" => route_table.route_table_id, "attributes" => attributes } } resources end end private def routes_of(route_table) route_table.routes.reject do |route| route.gateway_id.to_s == 'local' || route.origin.to_s == 'EnableVgwRoutePropagation' || route.destination_prefix_list_id end end def module_name_of(route_table) normalize_module_name(name_from_tag(route_table, route_table.route_table_id)) end def route_tables @client.describe_route_tables.map(&:route_tables).flatten end def routes_attributes_of(route_table) routes = routes_of(route_table) attributes = { "route.#" => routes.length.to_s } routes.each do |route| attributes.merge!(route_attributes_of(route)) end attributes end def route_attributes_of(route) hashcode = route_hashcode_of(route) attributes = { "route.#{hashcode}.cidr_block" => route.destination_cidr_block.to_s, "route.#{hashcode}.gateway_id" => route.gateway_id.to_s, "route.#{hashcode}.instance_id" => route.instance_id.to_s, "route.#{hashcode}.network_interface_id" => route.network_interface_id.to_s, "route.#{hashcode}.vpc_peering_connection_id" => route.vpc_peering_connection_id.to_s } attributes end def route_hashcode_of(route) string = "#{route.destination_cidr_block}-#{route.gateway_id}-" instance_set = !route.instance_id.nil? && route.instance_id != '' string << route.instance_id.to_s if instance_set string << route.vpc_peering_connection_id.to_s string << route.network_interface_id.to_s unless instance_set Zlib.crc32(string) end def propagaving_vgws_of(route_table) route_table.propagating_vgws.map(&:gateway_id).map(&:to_s) end def propagating_vgws_attributes_of(route_table) vgws = propagaving_vgws_of(route_table) attributes = { "propagating_vgws.#" => vgws.length.to_s } vgws.each do |gateway_id| hashcode = Zlib.crc32(gateway_id) attributes["propagating_vgws.#{hashcode}"] = gateway_id end attributes end def tags_attributes_of(route_table) tags = route_table.tags attributes = { "tags.#" => tags.length.to_s } tags.each { |tag| attributes["tags.#{tag.key}"] = tag.value } attributes end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/network_acl.rb
lib/terraforming/resource/network_acl.rb
module Terraforming module Resource class NetworkACL include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/network_acl") end def tfstate network_acls.inject({}) do |resources, network_acl| attributes = { "egress.#" => egresses_of(network_acl).length.to_s, "id" => network_acl.network_acl_id, "ingress.#" => ingresses_of(network_acl).length.to_s, "subnet_ids.#" => subnet_ids_of(network_acl).length.to_s, "tags.#" => network_acl.tags.length.to_s, "vpc_id" => network_acl.vpc_id, } resources["aws_network_acl.#{module_name_of(network_acl)}"] = { "type" => "aws_network_acl", "primary" => { "id" => network_acl.network_acl_id, "attributes" => attributes } } resources end end private def default_entry?(entry) entry.rule_number == default_rule_number end def default_rule_number 32767 end def egresses_of(network_acl) network_acl.entries.select { |entry| entry.egress && !default_entry?(entry) } end def from_port_of(entry) entry.port_range ? entry.port_range.from : 0 end def ingresses_of(network_acl) network_acl.entries.select { |entry| !entry.egress && !default_entry?(entry) } end def module_name_of(network_acl) normalize_module_name(name_from_tag(network_acl, network_acl.network_acl_id)) end def network_acls @client.describe_network_acls.map(&:network_acls).flatten end def subnet_ids_of(network_acl) network_acl.associations.map { |association| association.subnet_id } end def to_port_of(entry) entry.port_range ? entry.port_range.to : 0 end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/dynamo_db.rb
lib/terraforming/resource/dynamo_db.rb
module Terraforming module Resource class DynamoDB include Terraforming::Util def self.tf(client: Aws::DynamoDB::Client.new) self.new(client).tf end def self.tfstate(client: Aws::DynamoDB::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/dynamo_db") end def tfstate tables.inject({}) do |resources, dynamo_db_table| attributes = { "arn" => dynamo_db_table["table_arn"], "id" => dynamo_db_table["table_name"], "name" => dynamo_db_table["table_name"], "read_capacity" => dynamo_db_table["provisioned_throughput"]["read_capacity_units"].to_s, "stream_arn" => dynamo_db_table["latest_stream_arn"].to_s, "stream_label" => dynamo_db_table["latest_stream_label"].to_s, "write_capacity" => dynamo_db_table["provisioned_throughput"]["write_capacity_units"].to_s } attributes.merge!(attribute_definitions(dynamo_db_table)) attributes.merge!(global_indexes(dynamo_db_table)) attributes.merge!(local_indexes(dynamo_db_table)) attributes.merge!(key_schema(dynamo_db_table)) attributes.merge!(point_in_time_summary(dynamo_db_table)) attributes.merge!(sse_description(dynamo_db_table)) attributes.merge!(stream_specification(dynamo_db_table)) attributes.merge!(tags_of(dynamo_db_table)) attributes.merge!(ttl_of(dynamo_db_table)) resources["aws_dynamodb_table.#{module_name_of(dynamo_db_table)}"] = { "type" => "aws_dynamodb_table", "primary" => { "id" => dynamo_db_table.table_name, "attributes" => attributes, "meta" => { "schema_version" => "1" } } } resources end end private def tables tables = [] dynamo_db_tables.each do |table| attributes = @client.describe_table({ table_name: table }).table tables << attributes end return tables end def attribute_definitions(dynamo_db_table) attributes = { "attribute.#" => dynamo_db_table["attribute_definitions"].length.to_s} dynamo_db_table["attribute_definitions"].each do |attr_defn| attributes.merge!(attributes_definitions_of(attr_defn)) end attributes end def attributes_definitions_of(attr_defn) hashcode = attribute_hashcode(attr_defn) attributes = { "attribute.#{hashcode}.name" => attr_defn.attribute_name, "attribute.#{hashcode}.type" => attr_defn.attribute_type, } attributes end def attribute_hashcode(attr_defn) hashcode = Zlib.crc32(attr_defn.attribute_name+"-") end def global_indexes(dynamo_db_table) attributes = {} if dynamo_db_table["global_secondary_indexes"] attributes = { "global_secondary_index.#" => dynamo_db_table["global_secondary_indexes"].length.to_s} dynamo_db_table["global_secondary_indexes"].each do |global_sec_index| attributes.merge!(global_secondary_indexes_of(global_sec_index)) end end return attributes end def global_secondary_indexes_of(global_sec_index) attributes = global_indexes_of(global_sec_index).merge!(global_index_non_key_attributes(global_sec_index)) end def global_indexes_of(global_sec_index) hashcode = global_index_hashcode(global_sec_index) attributes = { "global_secondary_index.#{hashcode}.hash_key" => find_key(global_sec_index,"HASH"), "global_secondary_index.#{hashcode}.name" => global_sec_index.index_name, "global_secondary_index.#{hashcode}.projection_type" => global_sec_index.projection.projection_type, "global_secondary_index.#{hashcode}.range_key" => find_key(global_sec_index,"RANGE"), "global_secondary_index.#{hashcode}.read_capacity" => global_sec_index.provisioned_throughput.read_capacity_units.to_s , "global_secondary_index.#{hashcode}.write_capacity" => global_sec_index.provisioned_throughput.write_capacity_units.to_s, } attributes end def find_key(index,key_type) index["key_schema"].each do |schema| if schema.key_type == key_type return schema.attribute_name else return "" end end end def global_index_non_key_attributes(global_sec_index) attributes = {} if !global_sec_index["projection"]["non_key_attributes"].nil? hashcode = global_index_hashcode(global_sec_index) attributes = {"global_secondary_index.#{hashcode}.non_key_attributes.#" => global_sec_index["projection"]["non_key_attributes"].length.to_s} (0..global_sec_index["projection"]["non_key_attributes"].length.to_i-1).each do |index| attributes.merge!({"global_secondary_index.#{hashcode}.non_key_attributes.#{index}" => global_sec_index["projection"]["non_key_attributes"][index]}) end end attributes end def global_index_hashcode(global_sec_index) Zlib.crc32(global_sec_index["index_name"]+"-") end def local_indexes(dynamo_db_table) attributes = {} if dynamo_db_table["local_secondary_indexes"] attributes = {"local_secondary_index.#" => dynamo_db_table["local_secondary_indexes"].length.to_s} dynamo_db_table["local_secondary_indexes"].each do |local_sec_index| attributes.merge!(local_secondary_indexes_of(local_sec_index)) end end return attributes end def local_secondary_indexes_of(local_sec_index) attributes = {} hashcode = local_index_hashcode(local_sec_index) attributes.merge!("local_secondary_index.#{hashcode}.range_key" => find_key(local_sec_index,"RANGE")) if !find_key(local_sec_index,"RANGE").empty? attributes.merge!({ "local_secondary_index.#{hashcode}.name" => local_sec_index.index_name, "local_secondary_index.#{hashcode}.projection_type" => local_sec_index.projection.projection_type, }) attributes.merge!(local_index_non_key_attributes(local_sec_index)) attributes end def local_index_non_key_attributes(local_sec_index) attributes = {} if !local_sec_index["projection"]["non_key_attributes"].nil? hashcode = local_index_hashcode(local_sec_index) attributes = {"local_secondary_index.#{hashcode}.non_key_attributes.#" => local_sec_index["projection"]["non_key_attributes"].length.to_s} (0..local_sec_index["projection"]["non_key_attributes"].length.to_i-1).each do |index| attributes.merge!({"local_secondary_index.#{hashcode}.non_key_attributes.#{index}" => local_sec_index["projection"]["non_key_attributes"][index]}) end end attributes end def local_index_hashcode(local_index) Zlib.crc32(local_index["index_name"]+"-") end def key_schema(dynamo_db_table) attributes = {} if dynamo_db_table["key_schema"] attributes = {"key_schema.#" => dynamo_db_table["key_schema"].length.to_s} if !find_key(dynamo_db_table,"HASH").empty? attributes.merge!({"hash_key" => find_key(dynamo_db_table,"HASH")}) end end attributes end def point_in_time_summary(dynamo_db_table) resp = @client.describe_continuous_backups({ table_name: dynamo_db_table["table_name"] }) if resp.continuous_backups_description.point_in_time_recovery_description.point_in_time_recovery_status == "ENABLED" attributes = {"point_in_time_recovery.#" => 1.to_s} attributes.merge!({"point_in_time_recovery.0.enabled" => true.to_s}) else attributes = {"point_in_time_recovery.#" => 0.to_s} end end def sse_description(dynamo_db_table) attributes = {} if dynamo_db_table.sse_description if dynamo_db_table.sse_description.status == "ENABLED" attributes = {"server_side_encryption.#" => 1.to_s} attributes.merge!({"server_side_encryption.0.enabled" => true.to_s}) end else attributes.merge!({"server_side_encryption.#" => 0.to_s}) end attributes end def stream_specification(dynamo_db_table) attributes = {} if dynamo_db_table.stream_specification attributes = {"stream_view_type" => dynamo_db_table.stream_specification.stream_view_type} if dynamo_db_table.stream_specification.stream_enabled end attributes end def ttl_of(dynamo_db_table) attributes = {} ttl = ttl_values(dynamo_db_table) if !ttl.empty? hashcode = ttl_hashcode(ttl.first) attributes = {"ttl.#" => 1.to_s} attributes["ttl.#{hashcode}.attribute_name"] = ttl.first attributes["ttl.#{hashcode}.enabled"] = true.to_s end return attributes end def ttl_hashcode(attribute) Zlib.crc32(attribute) end def tags_of(dynamo_db_table) attributes = {} tags = tags(dynamo_db_table) if !tags.empty? attributes = { "tags.%" => tags.length.to_s } tags.each do |tag| attributes["tags.#{tag.key}"] = tag.value end end attributes end def dynamo_db_tables a = @client.list_tables.map(&:table_names).flatten end def ttl_values(dynamo_db_table) ttl = @client.describe_time_to_live({ table_name: dynamo_db_table.table_name }).time_to_live_description if ttl.time_to_live_status == "ENABLED" return [ttl.attribute_name] else return [] end end def tags(dynamo_db_table) resp = @client.list_tags_of_resource({resource_arn: dynamo_db_table.table_arn}).tags end def module_name_of(dynamo_db_table) normalize_module_name(dynamo_db_table['table_name']) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/route53_zone.rb
lib/terraforming/resource/route53_zone.rb
module Terraforming module Resource class Route53Zone include Terraforming::Util def self.tf(client: Aws::Route53::Client.new) self.new(client).tf end def self.tfstate(client: Aws::Route53::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/route53_zone") end def tfstate hosted_zones.inject({}) do |resources, hosted_zone| zone_id = zone_id_of(hosted_zone) vpc = vpc_of(hosted_zone) attributes = { "comment" => comment_of(hosted_zone), "id" => zone_id, "name" => name_of(hosted_zone), "name_servers.#" => name_servers_of(hosted_zone).length.to_s, "tags.#" => tags_of(hosted_zone).length.to_s, "vpc_id" => vpc ? vpc.vpc_id : "", "vpc_region" => vpc ? vpc.vpc_region : "", "zone_id" => zone_id, } resources["aws_route53_zone.#{module_name_of(hosted_zone)}"] = { "type" => "aws_route53_zone", "primary" => { "id" => zone_id, "attributes" => attributes, } } resources end end private def hosted_zones @client.list_hosted_zones.map(&:hosted_zones).flatten.map { |hosted_zone| @client.get_hosted_zone(id: hosted_zone.id) } end def tags_of(hosted_zone) @client.list_tags_for_resource(resource_type: "hostedzone", resource_id: zone_id_of(hosted_zone)).resource_tag_set.tags end def comment_of(hosted_zone) hosted_zone.hosted_zone.config.comment end def name_of(hosted_zone) hosted_zone.hosted_zone.name.gsub(/\.\z/, "") end def name_servers_of(hosted_zone) delegation_set = hosted_zone.delegation_set delegation_set ? delegation_set.name_servers : [] end def module_name_of(hosted_zone) normalize_module_name(name_of(hosted_zone)) << "-#{private_hosted_zone?(hosted_zone) ? 'private' : 'public'}" end def private_hosted_zone?(hosted_zone) hosted_zone.hosted_zone.config.private_zone end def vpc_of(hosted_zone) hosted_zone.vp_cs[0] end def zone_id_of(hosted_zone) hosted_zone.hosted_zone.id.gsub(%r{\A/hostedzone/}, "") end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/nat_gateway.rb
lib/terraforming/resource/nat_gateway.rb
module Terraforming module Resource class NATGateway include Terraforming::Util def self.tf(client: Aws::EC2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::EC2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/nat_gateway") end def tfstate nat_gateways.inject({}) do |resources, nat_gateway| next resources if nat_gateway.nat_gateway_addresses.empty? attributes = { "id" => nat_gateway.nat_gateway_id, "allocation_id" => nat_gateway.nat_gateway_addresses[0].allocation_id, "subnet_id" => nat_gateway.subnet_id, "network_inferface_id" => nat_gateway.nat_gateway_addresses[0].network_interface_id, "private_ip" => nat_gateway.nat_gateway_addresses[0].private_ip, "public_ip" => nat_gateway.nat_gateway_addresses[0].public_ip, } resources["aws_nat_gateway.#{module_name_of(nat_gateway)}"] = { "type" => "aws_nat_gateway", "primary" => { "id" => nat_gateway.nat_gateway_id, "attributes" => attributes } } resources end end private def nat_gateways @client.describe_nat_gateways.nat_gateways end def module_name_of(nat_gateway) normalize_module_name(nat_gateway.nat_gateway_id) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/alb.rb
lib/terraforming/resource/alb.rb
module Terraforming module Resource class ALB include Terraforming::Util def self.tf(client: Aws::ElasticLoadBalancingV2::Client.new) self.new(client).tf end def self.tfstate(client: Aws::ElasticLoadBalancingV2::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/alb") end def tfstate load_balancers.inject({}) do |resources, load_balancer| load_balancer_attributes = load_balancer_attributes_of(load_balancer) attributes = { "dns_name" => load_balancer.dns_name, "enable_deletion_protection" => load_balancer_attributes["deletion_protection.enabled"].to_s, "id" => load_balancer.load_balancer_arn, "idle_timeout" => load_balancer_attributes["idle_timeout.timeout_seconds"].to_s, "internal" => internal?(load_balancer).to_s, "name" => load_balancer.load_balancer_name, "security_groups.#" => load_balancer.security_groups.length.to_s, "subnets.#" => load_balancer.availability_zones.length.to_s, "zone_id" => load_balancer.canonical_hosted_zone_id, } attributes.merge!(access_logs_attributes_of(load_balancer_attributes)) attributes.merge!(tag_attributes_of(load_balancer)) resources["aws_alb.#{module_name_of(load_balancer)}"] = { "type" => "aws_alb", "primary" => { "id" => load_balancer.load_balancer_arn, "attributes" => attributes } } resources end end private def access_logs_attributes_of(load_balancer_attributes) { "access_logs.#" => "1", "access_logs.0.bucket" => load_balancer_attributes["access_logs.s3.bucket"], "access_logs.0.enabled" => load_balancer_attributes["access_logs.s3.enabled"].to_s, "access_logs.0.prefix" => load_balancer_attributes["access_logs.s3.prefix"], } end def internal?(load_balancer) load_balancer.scheme == "internal" end def load_balancers @client.describe_load_balancers.load_balancers end def load_balancer_attributes_of(load_balancer) @client.describe_load_balancer_attributes(load_balancer_arn: load_balancer.load_balancer_arn).attributes.inject({}) do |result, attribute| result[attribute.key] = attribute.value result end end def module_name_of(load_balancer) normalize_module_name(load_balancer.load_balancer_name) end def tag_attributes_of(load_balancer) tags = tags_of(load_balancer) attributes = { "tags.%" => tags.length.to_s } tags.each do |tag| attributes["tags.#{tag.key}"] = tag.value end attributes end def tags_of(load_balancer) @client.describe_tags(resource_arns: [load_balancer.load_balancer_arn]).tag_descriptions.first.tags end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/sns_topic.rb
lib/terraforming/resource/sns_topic.rb
module Terraforming module Resource class SNSTopic include Terraforming::Util def self.tf(client: Aws::SNS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::SNS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/sns_topic") end def tfstate topics.inject({}) do |resources, topic| attributes = { "name" => module_name_of(topic), "id" => topic["TopicArn"], "arn" => topic["TopicArn"], "display_name" => topic["DisplayName"], "policy" => topic.key?("Policy") ? topic["Policy"] : "", "delivery_policy" => topic.key?("DeliveryPolicy") ? topic["DeliveryPolicy"] : "" } resources["aws_sns_topic.#{module_name_of(topic)}"] = { "type" => "aws_sns_topic", "primary" => { "id" => topic["TopicArn"], "attributes" => attributes } } resources end end private def topics topic_arns.map do |topic_arn| attributes = @client.get_topic_attributes({ topic_arn: topic_arn, }).attributes attributes["TopicArn"] = topic_arn attributes end end def topic_arns token = "" arns = [] loop do resp = @client.list_topics(next_token: token) arns += resp.topics.map(&:topic_arn).flatten token = resp.next_token break if token.nil? end arns end def module_name_of(topic) normalize_module_name(topic["TopicArn"].split(":").last) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_group.rb
lib/terraforming/resource/iam_group.rb
module Terraforming module Resource class IAMGroup include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_group") end def tfstate iam_groups.inject({}) do |resources, group| attributes = { "arn" => group.arn, "id" => group.group_name, "name" => group.group_name, "path" => group.path, "unique_id" => group.group_id, } resources["aws_iam_group.#{module_name_of(group)}"] = { "type" => "aws_iam_group", "primary" => { "id" => group.group_name, "attributes" => attributes } } resources end end private def iam_groups @client.list_groups.map(&:groups).flatten end def module_name_of(group) normalize_module_name(group.group_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/iam_group_membership.rb
lib/terraforming/resource/iam_group_membership.rb
module Terraforming module Resource class IAMGroupMembership include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_group_membership") end def tfstate iam_groups.inject({}) do |resources, group| membership_name = membership_name_of(group) attributes = { "group" => group.group_name, "id" => membership_name, "name" => membership_name, "users.#" => group_members_of(group).length.to_s, } resources["aws_iam_group_membership.#{module_name_of(group)}"] = { "type" => "aws_iam_group_membership", "primary" => { "id" => membership_name, "attributes" => attributes } } resources end end private def group_members_of(group) @client.get_group(group_name: group.group_name).map(&:users).flatten.map(&:user_name) end def iam_groups @client.list_groups.map(&:groups).flatten end def membership_name_of(group) "#{group.group_name}-group-membership" end def module_name_of(group) normalize_module_name(group.group_name) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
dtan4/terraforming
https://github.com/dtan4/terraforming/blob/ab6486872952b61c4dca24d51a8a11f189f91573/lib/terraforming/resource/kms_alias.rb
lib/terraforming/resource/kms_alias.rb
module Terraforming module Resource class KMSAlias include Terraforming::Util def self.tf(client: Aws::KMS::Client.new) self.new(client).tf end def self.tfstate(client: Aws::KMS::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/kms_alias") end def tfstate aliases.inject({}) do |resources, als| resources["aws_kms_alias.#{module_name_of(als)}"] = { "type" => "aws_kms_alias", "primary" => { "id" => als.alias_name, "attributes" => { "arn" => als.alias_arn, "id" => als.alias_name, "name" => als.alias_name, "target_key_id" => als.target_key_id, }, }, } resources end end private def aliases @client.list_aliases.aliases.reject { |als| managed_master_key_alias?(als) } end def managed_master_key_alias?(als) als.alias_name =~ %r{\Aalias/aws/} end def module_name_of(als) normalize_module_name(als.alias_name.gsub(%r{\Aalias/}, "")) end end end end
ruby
MIT
ab6486872952b61c4dca24d51a8a11f189f91573
2026-01-04T15:46:47.062437Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/parallel_spec.rb
spec/parallel_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Parallel do worker_types = ["threads"] worker_types << "processes" if Process.respond_to?(:fork) worker_types << "ractors" if defined?(Ractor) def time_taken t = Time.now.to_f yield RUBY_ENGINE == "jruby" ? 0 : Time.now.to_f - t # jruby is super slow ... don't blow up all the tests ... end def kill_process_with_name(file, signal = 'INT') running_processes = `ps -f`.split("\n").map { |line| line.split(/\s+/) } pid_index = running_processes.detect { |p| p.include?("UID") }.index("UID") + 1 parent_pid = running_processes.detect { |p| p.include?(file) and !p.include?("sh") }[pid_index] `kill -s #{signal} #{parent_pid}` end def execute_start_and_kill(command, amount, signal = 'INT') t = nil lambda { t = Thread.new { ruby("spec/cases/parallel_start_and_kill.rb #{command} 2>&1 && echo 'FINISHED'") } sleep 1.5 kill_process_with_name('spec/cases/parallel_start_and_kill.rb', signal) sleep 1 }.should change { `ps`.split("\n").size }.by amount t.value end def without_ractor_warning(out) out.sub(/.*Ractor is experimental.*\n/, "") end describe ".processor_count" do before do Parallel.instance_variable_set(:@processor_count, nil) end it "returns a number" do (1..999).should include(Parallel.processor_count) end if RUBY_PLATFORM =~ /darwin10/ it 'works if hwprefs in not available' do Parallel.should_receive(:hwprefs_available?).and_return false (1..999).should include(Parallel.processor_count) end end end describe ".physical_processor_count" do before do Parallel.instance_variable_set(:@physical_processor_count, nil) end it "returns a number" do (1..999).should include(Parallel.physical_processor_count) end it "is even factor of logical cpus" do (Parallel.processor_count % Parallel.physical_processor_count).should == 0 end end describe ".in_processes" do def cpus Parallel.processor_count end it "executes with detected cpus" do ruby("spec/cases/parallel_with_detected_cpus.rb").should == "HELLO\n" * cpus end it "executes with detected cpus when nil was given" do ruby("spec/cases/parallel_with_nil_uses_detected_cpus.rb").should == "HELLO\n" * cpus end it "executes with cpus from ENV" do `PARALLEL_PROCESSOR_COUNT=10 ruby spec/cases/parallel_with_detected_cpus.rb`.should == "HELLO\n" * 10 end it "set amount of parallel processes" do ruby("spec/cases/parallel_with_set_processes.rb").should == "HELLO\n" * 5 end it "enforces only one worker type" do -> { Parallel.map([1, 2, 3], in_processes: 2, in_threads: 3) }.should raise_error(ArgumentError) end it "does not influence outside data" do ruby("spec/cases/parallel_influence_outside_data.rb").should == "yes" end it "kills the processes when the main process gets killed through ctrl+c" do time_taken do result = execute_start_and_kill "PROCESS", 0 result.should_not include "FINISHED" end.should be <= 3 end it "kills the processes when the main process gets killed through a custom interrupt" do time_taken do execute_start_and_kill "PROCESS SIGTERM", 0, "TERM" end.should be <= 3 end it "kills the threads when the main process gets killed through ctrl+c" do time_taken do result = execute_start_and_kill "THREAD", 0 result.should_not include "FINISHED" end.should be <= 3 end it "does not kill processes when the main process gets sent an interrupt besides the custom interrupt" do time_taken do result = execute_start_and_kill "PROCESS SIGTERM", 4 result.should include 'FINISHED' result.should include 'Wrapper caught SIGINT' result.should include 'I should have been killed earlier' end.should be <= 7 end it "does not kill threads when the main process gets sent an interrupt besides the custom interrupt" do time_taken do result = execute_start_and_kill "THREAD SIGTERM", 2 result.should include 'FINISHED' result.should include 'Wrapper caught SIGINT' result.should include 'I should have been killed earlier' end.should be <= 7 end it "does not kill anything on ctrl+c when everything has finished" do time_taken do t = Thread.new { ruby("spec/cases/parallel_fast_exit.rb 2>&1") } sleep 2 kill_process_with_name("spec/cases/parallel_fast_exit.rb") # simulates Ctrl+c sleep 1 result = t.value result.scan("I finished").size.should == 3 result.should_not include("Parallel execution interrupted") end.should <= 4 end it "preserves original intrrupts" do t = Thread.new { ruby("spec/cases/double_interrupt.rb 2>&1 && echo FIN") } sleep 2 kill_process_with_name("spec/cases/double_interrupt.rb") # simulates Ctrl+c sleep 1 result = t.value result.should include("YES") result.should include("FIN") end it "restores original intrrupts" do ruby("spec/cases/after_interrupt.rb 2>&1").should == "DEFAULT\n" end it "saves time" do time_taken do ruby("spec/cases/parallel_sleeping_2.rb") end.should < 3.5 end it "raises when one of the processes raises" do ruby("spec/cases/parallel_raise.rb").strip.should == 'TEST' end it "can raise an undumpable exception" do out = ruby("spec/cases/parallel_raise_undumpable.rb").strip out.sub!(Dir.pwd, '.') # relative paths out.gsub!(/(\d+):.*/, "\\1") # no diff in ruby version xyz.rb:123:in `block in <main>' out.should == "MyException: MyException\nBACKTRACE: spec/cases/parallel_raise_undumpable.rb:14" end it "can handle Break exceptions when the better_errors gem is installed" do out = ruby("spec/cases/parallel_break_better_errors.rb").strip out.should == "NOTHING WAS RAISED" end it 'can handle to high fork rate' do next if RbConfig::CONFIG["target_os"].include?("darwin1") # kills macs for some reason ruby("spec/cases/parallel_high_fork_rate.rb").should == 'OK' end it 'does not leave processes behind while running' do ruby("spec/cases/closes_processes_at_runtime.rb").gsub(/.* deprecated; use BigDecimal.*\n/, '').should == 'OK' end it "does not open unnecessary pipes" do max = (RbConfig::CONFIG["target_os"].include?("darwin1") ? 10 : 1800) # somehow super bad on CI ruby("spec/cases/count_open_pipes.rb").to_i.should < max end end describe ".in_threads" do it "saves time" do time_taken do Parallel.in_threads(3) { sleep 2 } end.should < 3 end it "does not create new processes" do -> { Thread.new { Parallel.in_threads(2) { sleep 1 } } }.should_not(change { `ps`.split("\n").size }) end it "returns results as array" do Parallel.in_threads(4) { |i| "XXX#{i}" }.should == ["XXX0", 'XXX1', 'XXX2', 'XXX3'] end it "raises when a thread raises" do Thread.report_on_exception = false -> { Parallel.in_threads(2) { |_i| raise "TEST" } }.should raise_error("TEST") ensure Thread.report_on_exception = true end end describe ".map" do it "saves time" do time_taken do ruby("spec/cases/parallel_map_sleeping.rb") end.should <= 3.5 end it "does not modify options" do -> { Parallel.map([], {}.freeze) }.should_not raise_error end it "executes with given parameters" do ruby("spec/cases/parallel_map.rb").should == "-a- -b- -c- -d-" end it "can dump/load complex objects" do ruby("spec/cases/parallel_map_complex_objects.rb").should == "YES" end it "starts new process immediately when old exists" do time_taken do ruby("spec/cases/parallel_map_uneven.rb") end.should <= 3.5 end it "does not flatten results" do Parallel.map([1, 2, 3], in_threads: 2) { |x| [x, x] }.should == [[1, 1], [2, 2], [3, 3]] end it "can run in threads" do result = Parallel.map([1, 2, 3, 4, 5, 6, 7, 8, 9], in_threads: 4) { |x| x + 2 } result.should == [3, 4, 5, 6, 7, 8, 9, 10, 11] end it 'supports all Enumerable-s' do ruby("spec/cases/parallel_map_range.rb").should == '[1, 2, 3, 4, 5]' end it 'handles nested arrays and nil correctly' do ruby("spec/cases/map_with_nested_arrays_and_nil.rb").should == '[nil, [2, 2], [[3], [3]]]' end worker_types.each do |type| it "does not queue new work when one fails in #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_exception.rb 2>&1` without_ractor_warning(out).should =~ /\A\d{4} raised\z/ end it "does not queue new work when one raises Break in #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_break.rb 2>&1` without_ractor_warning(out).should =~ /\A\d{4} Parallel::Break raised - result nil\z/ end it "stops all workers when a start hook fails with #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_exception_in_start.rb 2>&1` out = without_ractor_warning(out) if type == "ractors" # TODO: running ractors should be interrupted out.should =~ /\A.*raised.*\z/ out.should_not =~ /5/ # stopped at 4 else out.should =~ /\A\d{3} raised\z/ end end it "does not add new work when a finish hook fails with #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_exception_in_finish.rb 2>&1` without_ractor_warning(out).should =~ /\A\d{4} raised\z/ end it "does not call the finish hook when a worker fails with #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_exception_before_finish.rb 2>&1` without_ractor_warning(out).should == '3 called' end it "does not call the finish hook when a worker raises Break in #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_break_before_finish.rb 2>&1` without_ractor_warning(out).should =~ /\A\d{3}(finish hook called){3} Parallel::Break raised\z/ end it "does not call the finish hook when a start hook fails with #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_exception_in_start_before_finish.rb 2>&1` if type == "ractors" # we are calling on the main thread, so everything sleeps without_ractor_warning(out).should == "start 0\n" else out.split("\n").sort.join("\n").should == <<~OUT.rstrip call 3 finish 2 start 0 start 1 start 2 start 3 OUT end end it "can return from break with #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_break.rb hi 2>&1` out.should =~ /^\d{4} Parallel::Break raised - result "hi"$/ end it "sets Parallel.worker_number with 4 #{type}" do skip if type == "ractors" # not supported out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_worker_number.rb 2>&1` out.should =~ /\A[0123]+\z/ ['0', '1', '2', '3'].each { |number| out.should include number } end it "sets Parallel.worker_number with 0 #{type}" do skip if type == "ractors" # not supported type_key = :"in_#{type}" result = Parallel.map([1, 2, 3, 4, 5, 6, 7, 8, 9], type_key => 0) { |_x| Parallel.worker_number } result.uniq.should == [0] Parallel.worker_number.should be_nil end it "can run with 0 by not using #{type}" do Thread.should_not_receive(:exclusive) Process.should_not_receive(:fork) result = Parallel.map([1, 2, 3, 4, 5, 6, 7, 8, 9], "in_#{type}": 0) { |x| x + 2 } result.should == [3, 4, 5, 6, 7, 8, 9, 10, 11] end it "does not dump/load when running with 0 using #{type}" do p = -> { 1 } result = Parallel.map([1, 2], "in_#{type}": 0) { p } result.first.call.should == 1 end it "can call finish hook in order #{type}" do out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/finish_in_order.rb 2>&1` without_ractor_warning(out).should == <<~OUT finish nil 0 nil finish false 1 false finish 2 2 "F2" finish 3 3 "F3" finish 4 4 "F4" OUT end [0, 3].each do |count| it "notifies when an item of work is dispatched to #{count} worker using #{type}" do skip if type == "ractors" # TODO: why does this fail ? monitor = double('monitor', call: nil) monitor.should_receive(:call).once.with(:first, 0) monitor.should_receive(:call).once.with(:second, 1) monitor.should_receive(:call).once.with(:third, 2) Parallel.map([:first, :second, :third], start: monitor, "in_#{type}": 3) {} end it "notifies when an item of work is completed by #{count} worker using #{type}" do monitor = double('monitor', call: nil) monitor.should_receive(:call).once.with(:first, 0, 123) monitor.should_receive(:call).once.with(:second, 1, 123) monitor.should_receive(:call).once.with(:third, 2, 123) Parallel.map([:first, :second, :third], finish: monitor, in_processes: count) { 123 } end end end it "spits out a useful error when a worker dies before read" do ruby("spec/cases/map_with_killed_worker_before_read.rb 2>&1").should include "DEAD" end it "spits out a useful error when a worker dies before write" do ruby("spec/cases/map_with_killed_worker_before_write.rb 2>&1").should include "DEAD" end it "raises DeadWorker when using exit so people learn to not kill workers and do not crash main process" do ruby("spec/cases/exit_in_process.rb 2>&1").should include "Yep, DEAD" end it "rescues the Exception raised in child process" do ruby("spec/cases/exception_raised_in_process.rb 2>&1").should include "Yep, rescued the exception" end it 'raises EOF (not DeadWorker) when a worker raises EOF in process' do ruby("spec/cases/eof_in_process.rb 2>&1").should include 'Yep, EOF' end it "threads can be killed instantly" do mutex = Mutex.new state = [nil, nil] children = [nil, nil] thread = Thread.new do parent = Thread.current Parallel.map([0, 1], in_threads: 2) do |i| mutex.synchronize { children[i] = Thread.current } mutex.synchronize { state[i] = :ready } parent.join mutex.synchronize { state[i] = :error } end end Thread.pass while state.any?(&:nil?) thread.kill Thread.pass while children.any?(&:alive?) state[0].should == :ready state[1].should == :ready end it "processes can be killed instantly" do pipes = [IO.pipe, IO.pipe] thread = Thread.new do Parallel.map([0, 1, 2, 3], in_processes: 2) do |i| pipes[i % 2][0].close unless pipes[i % 2][0].closed? Marshal.dump('finish', pipes[i % 2][1]) sleep 1 nil end end [0, 1].each do |i| Marshal.load(pipes[i][0]).should == 'finish' end pipes.each { |pipe| pipe[1].close } thread.kill pipes.each do |pipe| begin ret = Marshal.load(pipe[0]) rescue EOFError ret = :error end ret.should == :error end pipes.each { |pipe| pipe[0].close } end it "synchronizes :start and :finish" do out = ruby("spec/cases/synchronizes_start_and_finish.rb") ['a', 'b', 'c'].each do |letter| out.sub! letter.downcase * 10, 'OK' out.sub! letter.upcase * 10, 'OK' end out.should == "OK\n" * 6 end it 'is equivalent to serial map' do l = Array.new(10_000) { |i| i } Parallel.map(l, { in_threads: 4 }) { |x| x + 1 }.should == l.map { |x| x + 1 } end it 'can work in isolation' do out = ruby("spec/cases/map_isolation.rb") out.should == "1\n2\n3\n4\nOK" end it 'sets Parallel.worker_number when run with isolation' do out = ruby("spec/cases/map_worker_number_isolation.rb") out.should == "0,1\nOK" end it 'can use Timeout' do out = ruby("spec/cases/timeout_in_threads.rb") out.should == "OK\n" end end describe ".map_with_index" do it "yields object and index" do ruby("spec/cases/map_with_index.rb 2>&1").should == 'a0b1' end it "does not crash with empty set" do ruby("spec/cases/map_with_index_empty.rb 2>&1").should == '' end it "can run with 0 threads" do Thread.should_not_receive(:exclusive) Parallel.map_with_index([1, 2, 3, 4, 5, 6, 7, 8, 9], in_threads: 0) do |x, _i| x + 2 end.should == [3, 4, 5, 6, 7, 8, 9, 10, 11] end it "can run with 0 processes" do Process.should_not_receive(:fork) Parallel.map_with_index([1, 2, 3, 4, 5, 6, 7, 8, 9], in_processes: 0) do |x, _i| x + 2 end.should == [3, 4, 5, 6, 7, 8, 9, 10, 11] end end describe ".flat_map" do it "yields object and index" do ruby("spec/cases/flat_map.rb 2>&1").should == '["a", ["a"], "b", ["b"]]' end end describe ".filter_map" do it "yields object" do ruby("spec/cases/filter_map.rb 2>&1").should == '["a", "c"]' end end describe ".any?" do it "returns true if any result is truthy" do ruby("spec/cases/any_true.rb").split(',').should == ['true'] * 3 * 2 end it "returns false if all results are falsy" do ruby("spec/cases/any_false.rb").split(',').should == ['false'] * 3 * 3 end end describe ".all?" do it "returns true if all results are truthy" do ruby("spec/cases/all_true.rb").split(',').should == ['true'] * 3 * 3 end it "returns false if any result is falsy" do ruby("spec/cases/all_false.rb").split(',').should == ['false'] * 3 * 2 end end describe ".each" do it "returns original array, works like map" do ruby("spec/cases/each.rb").should == 'a b c d' end it "passes result to :finish callback :in_processes`" do monitor = double('monitor', call: nil) monitor.should_receive(:call).once.with(:first, 0, 123) monitor.should_receive(:call).once.with(:second, 1, 123) monitor.should_receive(:call).once.with(:third, 2, 123) Parallel.each([:first, :second, :third], finish: monitor, in_processes: 3) { 123 } end it "passes result to :finish callback :in_threads`" do monitor = double('monitor', call: nil) monitor.should_receive(:call).once.with(:first, 0, 123) monitor.should_receive(:call).once.with(:second, 1, 123) monitor.should_receive(:call).once.with(:third, 2, 123) Parallel.each([:first, :second, :third], finish: monitor, in_threads: 3) { 123 } end it "does not use marshal_dump" do ruby("spec/cases/no_dump_with_each.rb 2>&1").should == 'no dump for resultno dump for each' end it "does not slow down with lots of GC work in threads" do Benchmark.realtime { ruby("spec/cases/no_gc_with_each.rb 2>&1") }.should <= 10 end it "can modify in-place" do ruby("spec/cases/each_in_place.rb").should == 'ab' end worker_types.each do |type| it "works with SQLite in #{type}" do out = `WORKER_TYPE=#{type} ruby spec/cases/each_with_ar_sqlite.rb 2>&1` out.gsub!(/.* deprecated; use BigDecimal.*\n/, '') skip "unsupported" if type == "ractors" without_ractor_warning(out).should == "Parent: X\nParallel: XXX\nParent: X\n" end it "stops all workers when one fails in #{type}" do `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_exception.rb 2>&1`.should =~ /^\d{4} raised$/ end it "stops all workers when one raises Break in #{type}" do out = `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_break.rb 2>&1` without_ractor_warning(out).should =~ /^\d{4} Parallel::Break raised - result nil$/ end it "stops all workers when a start hook fails with #{type}" do out = `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_exception_in_start.rb 2>&1` without_ractor_warning(out).should =~ /^\d{3} raised$/ end it "does not add new work when a finish hook fails with #{type}" do out = `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_exception_in_finish.rb 2>&1` without_ractor_warning(out).should =~ /^\d{4} raised$/ end it "does not call the finish hook when a worker fails with #{type}" do out = `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_exception_before_finish.rb 2>&1` without_ractor_warning(out).should == '3 called' end it "does not call the finish hook when a worker raises Break in #{type}" do out = `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_break_before_finish.rb 2>&1` out.should =~ /^\d{3}(finish hook called){3} Parallel::Break raised$/ end it "does not call the finish hook when a start hook fails with #{type}" do out = `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_exception_in_start_before_finish.rb 2>&1` if type == "ractors" # we are calling on the main thread, so everything sleeps without_ractor_warning(out).should == "start 0\n" else out.split("\n").sort.join("\n").should == <<~OUT.rstrip call 3 finish 2 start 0 start 1 start 2 start 3 OUT end end it "sets Parallel.worker_number with #{type}" do skip "unsupported" if type == "ractors" out = `METHOD=each WORKER_TYPE=#{type} ruby spec/cases/with_worker_number.rb 2>&1` out.should =~ /\A[0123]+\z/ ['0', '1', '2', '3'].each { |number| out.should include number } end end it "re-raises exceptions in work_direct" do `METHOD=each WORKER_TYPE=threads WORKER_SIZE=0 ruby spec/cases/with_exception.rb 2>&1` .should =~ /^1 raised$/ end it "handles Break in work_direct" do `METHOD=each WORKER_TYPE=threads WORKER_SIZE=0 ruby spec/cases/with_break.rb 2>&1` .should =~ /^1 Parallel::Break raised - result nil$/ end end describe ".each_with_index" do it "yields object and index" do ["a0b1", "b1a0"].should include ruby("spec/cases/each_with_index.rb 2>&1") end end describe "progress" do it "takes the title from :progress" do ruby("spec/cases/progress.rb 2>&1").sub(/=+/, '==').strip.should == "Doing stuff: |==|" end it "takes true from :progress" do `TITLE=true ruby spec/cases/progress.rb 2>&1`.sub(/=+/, '==').strip.should == "Progress: |==|" end it "works with :finish" do ruby("spec/cases/progress_with_finish.rb 2>&1").strip.sub(/=+/, '==').gsub( /\n+/, "\n" ).should == "Doing stuff: |==|\n100" end it "takes the title from :progress[:title] and passes options along" do ruby("spec/cases/progress_with_options.rb 2>&1").should =~ /Reticulating Splines ;+ \d+ ;+/ end end ["lambda", "queue"].each do |thing| describe thing do let(:result) { "ITEM-1\nITEM-2\nITEM-3\n" } worker_types.each do |type| it "runs in #{type}" do out = ruby("spec/cases/with_#{thing}.rb #{type} 2>&1") without_ractor_warning(out).should == result end end it "refuses to use progress" do lambda { Parallel.map(-> {}, progress: "xxx") { raise "Ooops" } # rubocop:disable Lint/UnreachableLoop }.should raise_error("Progressbar can only be used with array like items") end end end it "fails when running with a prefilled queue without stop since there are no threads to fill it" do error = (RUBY_VERSION >= "2.0.0" ? "No live threads left. Deadlock?" : "deadlock detected (fatal)") ruby("spec/cases/fatal_queue.rb 2>&1").should include error end describe "GC" do def normalize(result) result = result.sub(/\{(.*)\}/, "\\1").split(", ") result.reject! { |x| x =~ /^(Hash|Array|String)=>(1|-1|-2)$/ } result.reject! { |x| x =~ /^(Thread::Mutex)=>(1)$/ } if RUBY_VERSION >= "3.3" result end worker_types.each do |type| it "does not leak memory in #{type}" do pending if RUBY_ENGINE == 'jruby' # lots of objects ... GC does not seem to work ... skip if RUBY_VERSION > "3.4.0" # randomly fails, so can't use pending options = (RUBY_ENGINE == 'jruby' ? "-X+O" : "") result = ruby("#{options} spec/cases/profile_memory.rb #{type} 2>&1").strip.split("\n").last normalize(result).should == [] end end end end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require 'parallel' require 'benchmark' require 'timeout' RSpec.configure do |config| config.expect_with(:rspec) { |c| c.syntax = :should } config.mock_with(:rspec) { |c| c.syntax = :should } config.around { |example| Timeout.timeout(30, &example) } config.include( Module.new do def ruby(cmd) `#{RbConfig.ruby} #{cmd}` end end ) end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_with_index.rb
spec/cases/map_with_index.rb
# frozen_string_literal: true require './spec/cases/helper' result = Parallel.map_with_index(['a', 'b']) do |x, i| "#{x}#{i}" end print result * ''
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_sleeping_2.rb
spec/cases/parallel_sleeping_2.rb
# frozen_string_literal: true require './spec/cases/helper' Parallel.in_processes(5) do sleep 2 end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_start_and_kill.rb
spec/cases/parallel_start_and_kill.rb
# frozen_string_literal: true require './spec/cases/helper' method = case ARGV[0] when "PROCESS" then :in_processes when "THREAD" then :in_threads else raise "Learn to use this!" end options = {} options[:count] = 2 if ARGV.length > 1 options[:interrupt_signal] = ARGV[1].to_s trap('SIGINT') { puts 'Wrapper caught SIGINT' } if ARGV[1] != 'SIGINT' end Parallel.send(method, options) do sleep 5 puts "I should have been killed earlier..." end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/fatal_queue.rb
spec/cases/fatal_queue.rb
# frozen_string_literal: true require './spec/cases/helper' queue = Queue.new queue.push 1 queue.push 2 queue.push 3 Parallel.map(queue, in_threads: 2) { |(i, _id)| "ITEM-#{i}" }
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_with_ractor.rb
spec/cases/map_with_ractor.rb
# frozen_string_literal: true require './spec/cases/helper' class Callback def self.call(arg) "#{arg}x" end end result = Parallel.map(ENV['INPUT'].chars, in_ractors: Integer(ENV["COUNT"] || 2), ractor: [Callback, :call]) print result * ''
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_exception_before_finish.rb
spec/cases/with_exception_before_finish.rb
# frozen_string_literal: true require './spec/cases/helper' method = ENV.fetch('METHOD') in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}" class ParallelTestError < StandardError end class Callback def self.call(x) $stdout.sync = true if x != 3 sleep 0.2 raise ParallelTestError end print x x end end begin finish = lambda do |_item, _index, _result| print " called" end options = { in_worker_type => 4, finish: finish } if in_worker_type == :in_ractors Parallel.public_send(method, 1..10, options.merge(ractor: [Callback, :call])) else Parallel.public_send(method, 1..10, options) { |x| Callback.call x } end rescue ParallelTestError nil end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/profile_memory.rb
spec/cases/profile_memory.rb
# frozen_string_literal: true def count_objects old = Hash.new(0) cur = Hash.new(0) GC.start ObjectSpace.each_object { |o| old[o.class] += 1 } yield GC.start GC.start ObjectSpace.each_object { |o| cur[o.class] += 1 } cur.to_h { |k, v| [k, v - old[k]] }.reject { |_k, v| v == 0 } end class Callback def self.call(x); end end require './spec/cases/helper' items = Array.new(1000) options = { "in_#{ARGV[0]}": 2 } # TODO: not sure why this fails without 2.times in threading mode :( call = lambda do if ARGV[0] == "ractors" Parallel.map(items, options.merge(ractor: [Callback, :call])) sleep 0.1 # ractors need a bit to shut down else Parallel.map(items, options) {} end end puts(count_objects { 2.times { call.call } }.inspect) puts(count_objects { 2.times { call.call } }.inspect)
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_isolation.rb
spec/cases/map_isolation.rb
# frozen_string_literal: true require './spec/cases/helper' process_diff do result = Parallel.map([1, 2, 3, 4], in_processes: 2, isolation: true) do |i| @i ||= i end puts result end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_kill.rb
spec/cases/parallel_kill.rb
# frozen_string_literal: true require './spec/cases/helper' results = Parallel.map([1, 2, 3]) do |x| case x when 1 # -> stop all sub-processes, killing them instantly sleep 0.1 puts "DEAD" raise Parallel::Kill when 3 sleep 10 else x end end puts "Works #{results.inspect}"
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_map_complex_objects.rb
spec/cases/parallel_map_complex_objects.rb
# frozen_string_literal: true require './spec/cases/helper' object = ["\nasd#{File.read('Gemfile')}--#{File.read('Rakefile')}" * 100, 12_345, { b: :a }] result = Parallel.map([1, 2]) do |_x| object end print 'YES' if result.inspect == [object, object].inspect
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_with_killed_worker_before_read.rb
spec/cases/map_with_killed_worker_before_read.rb
# frozen_string_literal: true require './spec/cases/helper' begin Parallel.map([1, 2, 3]) do |_x, _i| Process.kill("SIGKILL", Process.pid) end rescue Parallel::DeadWorker puts "DEAD" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_break_before_finish.rb
spec/cases/with_break_before_finish.rb
# frozen_string_literal: true require './spec/cases/helper' method = ENV.fetch('METHOD') in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}" $stdout.sync = true class Callback def self.call(x) $stdout.sync = true sleep 0.1 # let workers start raise Parallel::Break if x == 1 sleep 0.2 print x x end end finish = lambda do |_item, _index, _result| sleep 0.1 print "finish hook called" end options = { in_worker_type => 4, finish: finish } if in_worker_type == :in_ractors Parallel.public_send(method, 1..10, options.merge(ractor: [Callback, :call])) else Parallel.public_send(method, 1..10, options) { |x| Callback.call x } end print " Parallel::Break raised"
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/no_dump_with_each.rb
spec/cases/no_dump_with_each.rb
# frozen_string_literal: true require './spec/cases/helper' class NotDumpable def marshal_dump raise "NOOOO" end def to_s 'not dumpable' end end Parallel.each([1]) do print 'no dump for result' NotDumpable.new end Parallel.each([NotDumpable.new]) do print 'no dump for each' 1 end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/any_true.rb
spec/cases/any_true.rb
# frozen_string_literal: true require './spec/cases/helper' $stdout.sync = true # otherwise results can go weird... results = [] [{ in_processes: 2 }, { in_threads: 2 }, { in_threads: 0 }].each do |options| x = [nil, nil, nil, nil, 42, nil, nil, nil] results << Parallel.any?(x, options) do |y| y end x = [true, true, true, false, true, true, true] results << Parallel.any?(x, options) do |y| y end end print results.join(',')
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/count_open_pipes.rb
spec/cases/count_open_pipes.rb
# frozen_string_literal: true require './spec/cases/helper' count = ->(*) { `lsof -l | grep pipe | wc -l`.to_i } start = count.call results = Parallel.map(Array.new(20), in_processes: 20, &count) puts results.max - start
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/any_false.rb
spec/cases/any_false.rb
# frozen_string_literal: true require './spec/cases/helper' $stdout.sync = true # otherwise results can go weird... results = [] [{ in_processes: 2 }, { in_threads: 2 }, { in_threads: 0 }].each do |options| x = [nil, nil, nil, nil, nil, nil, nil, nil] results << Parallel.any?(x, options) do |y| y end x = 10.times results << Parallel.any?(x, options) do |_y| false end # Empty array should return false x = [] results << Parallel.any?(x, options) do |y| y == 42 end end print results.join(',')
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_queue.rb
spec/cases/with_queue.rb
# frozen_string_literal: true require './spec/cases/helper' type = :"in_#{ARGV.fetch(0)}" class Callback def self.call(x) "ITEM-#{x}" end end queue = Queue.new Thread.new do sleep 0.2 queue.push 1 queue.push 2 queue.push 3 queue.push Parallel::Stop end if type == :in_ractors puts(Parallel.map(queue, type => 2, ractor: [Callback, :call])) else puts(Parallel.map(queue, type => 2) { |(i, _id)| Callback.call i }) end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/eof_in_process.rb
spec/cases/eof_in_process.rb
# frozen_string_literal: true require './spec/cases/helper' begin Parallel.map([1]) { raise EOFError } # rubocop:disable Lint/UnreachableLoop rescue EOFError puts 'Yep, EOF' else puts 'WHOOOPS' end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/exit_in_process.rb
spec/cases/exit_in_process.rb
# frozen_string_literal: true require './spec/cases/helper' begin Parallel.map([1]) { exit } # rubocop:disable Lint/UnreachableLoop rescue Parallel::DeadWorker puts "Yep, DEAD" else puts "WHOOOPS" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/double_interrupt.rb
spec/cases/double_interrupt.rb
# frozen_string_literal: true require './spec/cases/helper' Signal.trap :SIGINT do sleep 0.5 puts "YES" exit 0 end Parallel.map(Array.new(20), in_processes: 2) do sleep 10 puts "I should be killed earlier" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/closes_processes_at_runtime.rb
spec/cases/closes_processes_at_runtime.rb
# frozen_string_literal: true require './spec/cases/helper' process_diff do Parallel.each((0..10).to_a, in_processes: 5) { |a| raise unless a * 2 } end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_with_index_empty.rb
spec/cases/map_with_index_empty.rb
# frozen_string_literal: true require './spec/cases/helper' result = Parallel.map_with_index([]) do |x, i| "#{x}#{i}" end print result * ''
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_raise_undumpable.rb
spec/cases/parallel_raise_undumpable.rb
# frozen_string_literal: true require './spec/cases/helper' require 'stringio' class MyException < StandardError def initialize(object) super() @object = object end end begin Parallel.in_processes(2) do raise MyException, StringIO.new end puts "NOTHING WAS RAISED" rescue StandardError puts $!.message puts "BACKTRACE: #{$!.backtrace.first}" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_worker_number_isolation.rb
spec/cases/map_worker_number_isolation.rb
# frozen_string_literal: true require './spec/cases/helper' process_diff do result = Parallel.map([1, 2, 3, 4], in_processes: 2, isolation: true) do |_i| Parallel.worker_number end puts result.uniq.sort.join(',') end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/each_with_ar_sqlite.rb
spec/cases/each_with_ar_sqlite.rb
# frozen_string_literal: true require './spec/cases/helper' require "logger" require "active_record" require "sqlite3" require "tempfile" $stdout.sync = true in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}" Tempfile.create("db") do |temp| ActiveRecord::Schema.verbose = false ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: temp.path ) class User < ActiveRecord::Base # rubocop:disable Lint/ConstantDefinitionInBlock end class Callback # rubocop:disable Lint/ConstantDefinitionInBlock def self.call(_) $stdout.sync = true puts "Parallel: #{User.all.map(&:name).join}" end end # create tables unless User.table_exists? ActiveRecord::Schema.define(version: 1) do create_table :users do |t| t.string :name end end end User.delete_all 3.times { User.create!(name: "X") } puts "Parent: #{User.first.name}" if in_worker_type == :in_ractors Parallel.each([1], in_worker_type => 1, ractor: [Callback, :call]) else Parallel.each([1], in_worker_type => 1) { |x| Callback.call x } end puts "Parent: #{User.first.name}" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_exception_in_start.rb
spec/cases/with_exception_in_start.rb
# frozen_string_literal: true require './spec/cases/helper' method = ENV.fetch('METHOD') in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}" class ParallelTestError < StandardError end class Callback def self.call(x) $stdout.sync = true print x sleep 0.2 # so now no work gets queued before exception is raised x end end begin start = lambda do |_item, _index| @started = (@started ? @started + 1 : 1) sleep 0.01 # a bit of time for ractors to work raise ParallelTestError, 'foo' if @started == 4 end options = { in_worker_type => 4, start: start } if in_worker_type == :in_ractors Parallel.public_send(method, 1..10, options.merge(ractor: [Callback, :call])) else Parallel.public_send(method, 1..10, options) { |x| Callback.call x } end rescue ParallelTestError print ' raised' end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_break_better_errors.rb
spec/cases/parallel_break_better_errors.rb
# frozen_string_literal: true require './spec/cases/helper' require 'stringio' class MyException < StandardError def initialize(object) super() @object = object end end begin Parallel.in_processes(2) do ex = Parallel::Break.new # better_errors sets an instance variable that contains an array of bindings. ex.instance_variable_set :@__better_errors_bindings_stack, [ex.send(:binding)] raise ex end puts "NOTHING WAS RAISED" rescue StandardError puts $!.message puts "BACKTRACE: #{$!.backtrace.first}" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_raise.rb
spec/cases/parallel_raise.rb
# frozen_string_literal: true require './spec/cases/helper' begin Parallel.in_processes(2) do raise "TEST" end puts "FAIL" rescue RuntimeError puts $!.message end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_with_set_processes.rb
spec/cases/parallel_with_set_processes.rb
# frozen_string_literal: true require './spec/cases/helper' x = Parallel.in_processes(5) do "HELLO" end puts x
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_exception_in_finish.rb
spec/cases/with_exception_in_finish.rb
# frozen_string_literal: true require './spec/cases/helper' $stdout.sync = true method = ENV.fetch('METHOD') in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}" class ParallelTestError < StandardError end class Callback def self.call(x) $stdout.sync = true print x sleep 0.2 # let everyone start and print sleep 0.2 unless x == 1 # prevent other work from start/finish before exception x end end begin finish = lambda do |x, _index, _result| raise ParallelTestError, 'foo' if x == 1 end options = { in_worker_type => 4, finish: finish } if in_worker_type == :in_ractors Parallel.public_send(method, 1..10, options.merge(ractor: [Callback, :call])) else Parallel.public_send(method, 1..10, options) { |x| Callback.call x } end rescue ParallelTestError print ' raised' end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_map.rb
spec/cases/parallel_map.rb
# frozen_string_literal: true require './spec/cases/helper' result = Parallel.map(['a', 'b', 'c', 'd']) do |x| "-#{x}-" end print result * ' '
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_lambda.rb
spec/cases/with_lambda.rb
# frozen_string_literal: true require './spec/cases/helper' $stdout.sync = true type = :"in_#{ARGV.fetch(0)}" all = [3, 2, 1] produce = -> { all.pop || Parallel::Stop } class Callback def self.call(x) $stdout.sync = true "ITEM-#{x}" end end if type == :in_ractors puts(Parallel.map(produce, type => 2, ractor: [Callback, :call])) else puts(Parallel.map(produce, type => 2) { |(i, _id)| Callback.call i }) end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/all_false.rb
spec/cases/all_false.rb
# frozen_string_literal: true require './spec/cases/helper' $stdout.sync = true # otherwise results can go weird... results = [] [{ in_processes: 2 }, { in_threads: 2 }, { in_threads: 0 }].each do |options| x = [nil, nil, nil, nil, nil, nil, nil, nil] results << Parallel.all?(x, options) do |y| y end x = [42, 42, 42, 42, 42, 42, 42, 5, 42, 42, 42] results << Parallel.all?(x, options) do |y| y == 42 end end print results.join(',')
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/exception_raised_in_process.rb
spec/cases/exception_raised_in_process.rb
# frozen_string_literal: true require './spec/cases/helper' begin Parallel.each([1]) { raise StandardError } # rubocop:disable Lint/UnreachableLoop rescue Parallel::DeadWorker puts "No, DEAD worker found" rescue Exception # rubocop:disable Lint/RescueException puts "Yep, rescued the exception" else puts "WHOOOPS" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/synchronizes_start_and_finish.rb
spec/cases/synchronizes_start_and_finish.rb
# frozen_string_literal: true require './spec/cases/helper' start = lambda { |item, _index| print item * 5 sleep rand * 0.2 puts item * 5 } finish = lambda { |_item, _index, result| print result * 5 sleep rand * 0.2 puts result * 5 } Parallel.map(['a', 'b', 'c'], start: start, finish: finish) do |i| sleep rand * 0.2 i.upcase end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_high_fork_rate.rb
spec/cases/parallel_high_fork_rate.rb
# frozen_string_literal: true require './spec/cases/helper' Parallel.each((0..200).to_a, in_processes: 200) do |_x| sleep 1 end print 'OK'
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_influence_outside_data.rb
spec/cases/parallel_influence_outside_data.rb
# frozen_string_literal: true require './spec/cases/helper' x = 'yes' Parallel.in_processes(2) do x = 'no' end print x
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/each_with_index.rb
spec/cases/each_with_index.rb
# frozen_string_literal: true require './spec/cases/helper' Parallel.each_with_index(['a', 'b'], in_threads: 2) do |x, i| print "#{x}#{i}" end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/progress_with_options.rb
spec/cases/progress_with_options.rb
# frozen_string_literal: true require './spec/cases/helper' # ruby-progressbar ignores the format string you give it # unless the output is a TTY. When running in the test, # the output is not a TTY, so we cannot test that the format # string you pass overrides parallel's default. So, we pretend # that stdout is a TTY to test that the options are merged # in the correct way. tty_stdout = $stdout class << tty_stdout def tty? true end end parallel_options = { progress: { title: "Reticulating Splines", progress_mark: ';', format: "%t %w", output: tty_stdout } } Parallel.map(1..50, parallel_options) do 2 end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_with_ar.rb
spec/cases/map_with_ar.rb
# frozen_string_literal: true require './spec/cases/helper' require "active_record" database = "parallel_with_ar_test" `mysql #{database} -e '' || mysql -e 'create database #{database}'` ActiveRecord::Schema.verbose = false ActiveRecord::Base.establish_connection( adapter: "mysql2", database: database ) class User < ActiveRecord::Base end # create tables unless User.table_exists? ActiveRecord::Schema.define(version: 1) do create_table :users do |t| t.string :name end end end User.delete_all User.create!(name: "X") Parallel.map(1..8) do |i| User.create!(name: i) end puts "User.count: #{User.count}" puts User.connection.reconnect!.inspect Parallel.map(1..8, in_threads: 4) do |i| User.create!(name: i) end User.create!(name: "X") puts User.all.map(&:name).sort.join("-")
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_worker_number.rb
spec/cases/with_worker_number.rb
# frozen_string_literal: true require './spec/cases/helper' method = ENV.fetch('METHOD') in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}" Parallel.public_send(method, 1..100, in_worker_type => 4) do sleep 0.1 # so all workers get started print Parallel.worker_number end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_map_range.rb
spec/cases/parallel_map_range.rb
# frozen_string_literal: true require './spec/cases/helper' result = Parallel.map(1..5) do |x| x end print result.inspect
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_fast_exit.rb
spec/cases/parallel_fast_exit.rb
# frozen_string_literal: true require './spec/cases/helper' Parallel.map([1, 2, 3], in_processes: 2) do puts "I finished..." end sleep 10
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_map_sleeping.rb
spec/cases/parallel_map_sleeping.rb
# frozen_string_literal: true require './spec/cases/helper' Parallel.map(['a', 'b', 'c', 'd']) do |_x| sleep 1 end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_with_nil_uses_detected_cpus.rb
spec/cases/parallel_with_nil_uses_detected_cpus.rb
# frozen_string_literal: true require './spec/cases/helper' x = Parallel.in_processes(nil) do "HELLO" end puts x
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/each_in_place.rb
spec/cases/each_in_place.rb
# frozen_string_literal: true require './spec/cases/helper' $stdout.sync = true # otherwise results can go weird... x = [+'a'] Parallel.each(x, in_threads: 1) { |y| y << 'b' } print x.first
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false
grosser/parallel
https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_exception_in_start_before_finish.rb
spec/cases/with_exception_in_start_before_finish.rb
# frozen_string_literal: true require './spec/cases/helper' method = ENV.fetch('METHOD') in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}" $stdout.sync = true class ParallelTestError < StandardError end class Callback def self.call(x) $stdout.sync = true puts "call #{x}" x end end begin start = lambda do |item, index| puts "start #{index}" if item != 3 sleep 0.2 raise ParallelTestError end end finish = lambda do |_item, index, _result| puts "finish #{index}" end options = { in_worker_type => 4, start: start, finish: finish } if in_worker_type == :in_ractors Parallel.public_send(method, 1..10, options.merge(ractor: [Callback, :call])) else Parallel.public_send(method, 1..10, options) { |x| Callback.call x } end rescue ParallelTestError nil end
ruby
MIT
8d638d0d8e4c17dd74776557991e3aa73dfc8b07
2026-01-04T15:46:55.131598Z
false