{"id":20840062,"url":"https://github.com/ackama/aws_ec2_environment","last_synced_at":"2026-01-28T12:34:17.902Z","repository":{"id":57219953,"uuid":"527034758","full_name":"ackama/aws_ec2_environment","owner":"ackama","description":"A gem to help connecting to AWS EC2 instances using SSM, compatible with Capistrano","archived":false,"fork":false,"pushed_at":"2025-12-14T19:11:37.000Z","size":73,"stargazers_count":0,"open_issues_count":4,"forks_count":0,"subscribers_count":9,"default_branch":"main","last_synced_at":"2026-01-04T17:50:09.256Z","etag":null,"topics":["aws","capistrano","deployment","ec2","ssm"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ackama.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2022-08-20T20:39:11.000Z","updated_at":"2025-12-14T18:40:23.000Z","dependencies_parsed_at":"2024-07-20T02:19:04.030Z","dependency_job_id":"7a4e70b4-2e46-4ab3-98d0-ca878b421200","html_url":"https://github.com/ackama/aws_ec2_environment","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ackama/aws_ec2_environment","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ackama%2Faws_ec2_environment","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ackama%2Faws_ec2_environment/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ackama%2Faws_ec2_environment/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ackama%2Faws_ec2_environment/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ackama","download_url":"https://codeload.github.com/ackama/aws_ec2_environment/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ackama%2Faws_ec2_environment/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28845279,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-28T10:53:21.605Z","status":"ssl_error","status_checked_at":"2026-01-28T10:53:20.789Z","response_time":57,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","capistrano","deployment","ec2","ssm"],"created_at":"2024-11-18T01:15:09.290Z","updated_at":"2026-01-28T12:34:17.896Z","avatar_url":"https://github.com/ackama.png","language":"Ruby","readme":"# AwsEc2Environment\n\nA gem that makes it easier to interact with and deploy Ruby projects that are\nhosted on EC2 instances in AWS.\n\n## Installation\n\nInstall the gem and add to the application's Gemfile by executing:\n\n    $ bundle add aws_ec2_environment\n\nIf bundler is not being used to manage dependencies, install the gem by\nexecuting:\n\n    $ gem install aws_ec2_environment\n\n## Usage\n\nUse `AwsEc2Environment.from_yaml_file` to create a new representation of your\nEC2 environment from a config file:\n\n```ruby\nec2_env = AwsEc2Environment.from_yaml_file(\"./aws.yml\", :production)\n\n# this will ensure that any post-connection cleanup is handled, such as terminating\n# any SSM port forwarding sessions that are active\nat_exit { ec2_env.stop_ssh_port_forwarding_sessions } if ec2_env.config.use_ssm\n\n# this will return a list of hosts for sshing, handling any pre-connection setup\n# such as starting port forwarding sessions for each instance if SSM is enabled.\nec2_env.hosts_for_sshing\n```\n\n### Configuration\n\nThis is the most basic configuration you can have:\n\n```yaml\nproduction:\n  aws_region: ap-southeast-2\n  ssh_user: deploy\n  filters:\n    - name: 'instance-state-name'\n      values: ['running']\n    - name: 'tag:Name'\n      values: ['MyWebsiteProductionAppServerAsg']\n```\n\nAll the top level properties are required, and the `filters` key holds an array\nof filters that are used with the\n[`DescribeInstances` API endpoint](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html).\n\n### With bastion hosts\n\nYou can specify filters for a bastion instance too:\n\n```yaml\nproduction:\n  aws_region: ap-southeast-2\n  ssh_user: deploy\n  filters:\n    - name: 'instance-state-name'\n      values: ['running']\n    - name: 'tag:Name'\n      values: ['MyWebsiteProductionAppServerAsg']\n  bastion_instance:\n    ssh_user: bastion\n    filters:\n      - name: 'instance-state-name'\n        values: ['running']\n      - name: 'tag:Name'\n        values: ['MyWebsiteProductionBastionAsg']\n```\n\nNote that the filters should result in _one_ instance being returned, otherwise\nan error will be thrown.\n\nIf you use the same user as your application servers, you can pass an array of\nfilters as the value of the top-level property:\n\n```yaml\nproduction:\n  aws_region: ap-southeast-2\n  ssh_user: deploy\n  filters:\n    - name: 'instance-state-name'\n      values: ['running']\n    - name: 'tag:Name'\n      values: ['MyWebsiteProductionAppServerAsg']\n  bastion_instance:\n    - name: 'instance-state-name'\n      values: ['running']\n    - name: 'tag:Name'\n      values: ['MyWebsiteProductionBastionAsg']\n```\n\n#### With SSM\n\nIf your instances have the\n[SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)\n(preinstalled on some\n[AMIs](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html)),\nyou can use SSM to connect directly to instances even if they're in a private\nsubnet, via port forwarding:\n\n```yaml\nproduction:\n  aws_region: ap-southeast-2\n  ssh_user: deploy\n  ssm_host: 'ec2.#{id}.local.ackama.app'\n  use_ssm: true\n  filters:\n    - name: 'instance-state-name'\n      values: ['running']\n    - name: 'tag:Name'\n      values: ['MyWebsiteProductionAppServerAsg']\n```\n\n\u003e This requires the\n\u003e [`aws`](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)\n\u003e CLI and\n\u003e [`session-manager-plugin`](https://github.com/aws/session-manager-plugin) to\n\u003e be installed locally. These both come preinstalled on GitHub Actions runners,\n\u003e and are otherwise easy to install manually.\n\u003e\n\u003e - [Installing `aws` cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)\n\u003e - [Installing `session-manager-plugin`](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)\n\nYou can also specify an alternative hostname to use instead of `127.0.0.1` with\nthe `ssm_host` property - this is useful when working with tools like Capistrano\nthat only log the host _name_, so this property can let you ensure each instance\ncan be identified in the logs.\n\nThis property should be a host that resolves to `127.0.0.1`, and you can inject\nthe instance id with `#{id}`.\n\n\u003e Ackama provides `ec2.*.local.ackama.app` for this\n\n### With Capistrano\n\n```ruby\n# ./Capfile\n# ...\nrequire \"aws_ec2_environment\"\n\n# ./config/deploy/production.rb\nset :rails_env, \"production\"\nset :branch, \"production\"\n\nec2_env = AwsEc2Environment.from_yaml_file(\"./aws.yml\", :production)\n\nat_exit { ec2_env.stop_ssh_port_forwarding_sessions } if ec2_env.config.use_ssm\n\nssh_options = {}\n\nif ec2_env.use_bastion_server?\n  ssh_options[:proxy] = Net::SSH::Proxy::Command.new(ec2_env.build_ssh_bastion_proxy_command)\nend\n\nset :ssh_options, ssh_options\n\nrole(:app, ec2_env.hosts_for_sshing, user: ec2_env.config.ssh_user)\n```\n\n### With custom port forwarding\n\nYou can also use the `SsmPortForwardingSession` class directly to do port\nforwarding, which can be useful for things like custom rake tasks:\n\n```ruby\nrequire \"aws_ec2_environment\"\n\ntask :forward_port, %i[instance_id remote_port local_port] =\u003e :environment do |_, args|\n  # trap ctl+c to make things a bit nicer (otherwise we'll get an ugly stacktrace)\n  # since we expect this to be used to terminate the command\n  trap(\"SIGINT\") { exit }\n\n  logger = Logger.new($stdout)\n\n  instance_id = args.fetch(:instance_id)\n  remote_port = args.fetch(:remote_port)\n  local_port = args.fetch(:local_port, nil)\n\n  session = AwsEc2Environment::SsmPortForwardingSession.new(\n    instance_id,\n    remote_port,\n    local_port:,\n    logger:\n  )\n\n  at_exit { session.close }\n\n  local_port = session.wait_for_local_port\n\n  local_alias = \"ec2.#{instance_id}.local.ackama.app:#{local_port}\"\n  logger.info \"Use #{local_alias} to communicate with port #{remote_port} on #{instance_id}\"\n\n  loop { sleep 1 }\nend\n```\n\nYou can also use specific documents, and pass in extra parameters, which can be\nuseful for using tunnels to access other private resources like database\ninstances:\n\n```ruby\nrequire \"aws_ec2_environment\"\n\ndesc \"Dumps a copy of the postgres database using AWS and PG environment variables\"\ntask :dump_pg_database, %i[instance_id dump_file] =\u003e :environment do |_, args|\n  instance_id = args.fetch(:instance_id)\n  dump_file = args.fetch(:dump_file)\n\n  remote_host = ENV.fetch(\"PGHOST\")\n  remote_port = ENV.fetch(\"PGPORT\", 5432).to_i\n\n  session = AwsEc2Environment::SsmPortForwardingSession.new(\n    instance_id,\n    remote_port,\n    document: \"AWS-StartPortForwardingSessionToRemoteHost\",\n    extra_params: { \"host\" =\u003e [remote_host] }\n  )\n\n  at_exit { session.close }\n\n  local_port = session.wait_for_local_port\n\n  system(\n    \"pg_dump\",\n    \"--format=c\",\n    \"--no-owner\",\n    \"--no-privileges\",\n    \"--host=localhost\",\n    \"--port=#{local_port}\",\n    \"--file=#{dump_file}\",\n  )\nend\n```\n\n### AWS Authentication and Permissions\n\nSince this gem interacts with AWS, it must be configured with credentials - see\n[here](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/setup-config.html)\nfor how to do that.\n\n\u003e We recommend using\n\u003e [OpenID Connect](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)\n\u003e to authenticate with AWS when running in GitHub Actions.\n\nThe credentials must be for an identity that is allowed to perform the\n`ec2:DescribeInstances` action. If you're using SSM you must also allow the\n`ssm:StartSession` and `ssm:TerminateSession` actions.\n\nHere is a sample IAM policy document that grants these actions conditionally in\naccordance with the principle of least privilege:\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"AllowDescribingInstances\",\n      \"Effect\": \"Allow\",\n      \"Action\": \"ec2:DescribeInstances\",\n      \"Resource\": \"*\"\n    },\n    {\n      \"Sid\": \"AllowStartingPortForwardingSessions\",\n      \"Effect\": \"Allow\",\n      \"Action\": \"ssm:StartSession\",\n      \"Resource\": \"arn:aws:ssm:*::document/AWS-StartPortForwardingSession\"\n    },\n    {\n      \"Sid\": \"AllowStartingNewSessionsOnTaggedEC2Instances\",\n      \"Effect\": \"Allow\",\n      \"Action\": \"ssm:StartSession\",\n      \"Resource\": \"arn:aws:ec2:*:account-id:instance/*\",\n      \"Condition\": {\n        \"StringEquals\": {\n          \"ssm:resourceTag/Environment\": \"Production\",\n          \"ssm:resourceTag/Name\": \"MyWebsiteProductionAppServerAsg\"\n        }\n      }\n    },\n    {\n      \"Sid\": \"AllowTerminatingOwnSessions\",\n      \"Effect\": \"Allow\",\n      \"Action\": \"ssm:TerminateSession\",\n      \"Resource\": \"arn:aws:ssm:*:account-id:session/*\",\n      \"Condition\": {\n        \"StringLike\": {\n          \"ssm:resourceTag/aws:ssmmessages:session-id\": \"${aws:username}\"\n        }\n      }\n    }\n  ]\n}\n```\n\n\u003e Remember to replace \"account-id\" in the above document with the ID of your AWS\n\u003e account!\n\n\u003e If you are using a federated identity (such as GitHub's OpenID Connect\n\u003e provider), then you will need to replace `${aws:username}` with\n\u003e `${aws:userid}` - see\n\u003e [here](https://aws.amazon.com/premiumsupport/knowledge-center/iam-policy-variables-federated/)\n\u003e for more.\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run\n`rake spec` to run the tests. You can also run `bin/console` for an interactive\nprompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To\nrelease a new version, update the version number in `version.rb`, and then run\n`bundle exec rake release`, which will create a git tag for the version, push\ngit commits and the created tag, and push the `.gem` file to\n[rubygems.org](https://rubygems.org).\n\n## Contributing\n\nContributions are welcome. Please see the\n[contribution guidelines](CONTRIBUTING.md) for detailed instructions.\n\n## License\n\nThe gem is available as open source under the terms of the\n[MIT License](https://opensource.org/licenses/MIT).\n\n## Code of Conduct\n\nEveryone interacting in this project's codebases, issue trackers, chat rooms and\nmailing lists is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fackama%2Faws_ec2_environment","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fackama%2Faws_ec2_environment","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fackama%2Faws_ec2_environment/lists"}