Repository: test-kitchen/kitchen-ec2 Branch: main Commit: 355bbe91c87c Files: 50 Total size: 286.7 KB Directory structure: gitextract_xeolu7ld/ ├── .github/ │ ├── CODEOWNERS │ └── workflows/ │ ├── lint.yml │ └── publish.yaml ├── .gitignore ├── .markdownlint.yaml ├── .release-please-manifest.json ├── .rspec ├── .rubocop.yml ├── .tool-versions ├── .yardopts ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE ├── README.md ├── Rakefile ├── docs/ │ └── ssm-session-manager.md ├── kitchen-ec2.gemspec ├── lib/ │ └── kitchen/ │ └── driver/ │ ├── aws/ │ │ ├── client.rb │ │ ├── dedicated_hosts.rb │ │ ├── instance_connect.rb │ │ ├── instance_generator.rb │ │ ├── ssm_session_manager.rb │ │ ├── standard_platform/ │ │ │ ├── alma.rb │ │ │ ├── amazon.rb │ │ │ ├── amazon2.rb │ │ │ ├── amazon2023.rb │ │ │ ├── centos.rb │ │ │ ├── debian.rb │ │ │ ├── fedora.rb │ │ │ ├── freebsd.rb │ │ │ ├── macos.rb │ │ │ ├── rhel.rb │ │ │ ├── rocky.rb │ │ │ ├── ubuntu.rb │ │ │ └── windows.rb │ │ └── standard_platform.rb │ ├── ec2.rb │ └── ec2_version.rb ├── release-please-config.json ├── renovate.json └── spec/ ├── kitchen/ │ └── driver/ │ ├── aws/ │ │ ├── client_spec.rb │ │ ├── image_selection_spec.rb │ │ ├── instance_connect_test.rb │ │ ├── instance_generator_spec.rb │ │ ├── ssm_session_manager_spec.rb │ │ └── standard_platform_spec.rb │ └── ec2_spec.rb ├── spec_helper.rb └── support/ └── fake_image.rb ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/CODEOWNERS ================================================ @test-kitchen/maintainers ================================================ FILE: .github/workflows/lint.yml ================================================ --- name: "Test" "on": pull_request: jobs: lint-unit: uses: test-kitchen/.github/.github/workflows/lint-unit.yml@main ================================================ FILE: .github/workflows/publish.yaml ================================================ --- name: release-please "on": push: branches: [main] jobs: release-please: runs-on: ubuntu-latest steps: - uses: googleapis/release-please-action@v5 id: release with: token: ${{ secrets.PORTER_GITHUB_TOKEN }} - name: Checkout uses: actions/checkout@v6 if: ${{ steps.release.outputs.release_created }} - name: Build and publish to GitHub Package uses: actionshub/publish-gem-to-github@main if: ${{ steps.release.outputs.release_created }} with: token: ${{ secrets.GITHUB_TOKEN }} owner: ${{ secrets.OWNER }} - name: Build and publish to RubyGems uses: actionshub/publish-gem-to-rubygems@main if: ${{ steps.release.outputs.release_created }} with: token: ${{ secrets.RUBYGEMS_API_KEY }} ================================================ FILE: .gitignore ================================================ *.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage bin/ doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp .project .kitchen/ .kitchen.local.yml vendor/bundle/ ================================================ FILE: .markdownlint.yaml ================================================ --- default: true MD004: false MD012: false MD013: false MD024: false ================================================ FILE: .release-please-manifest.json ================================================ { ".": "3.22.3" } ================================================ FILE: .rspec ================================================ --color --require spec_helper --format documentation ================================================ FILE: .rubocop.yml ================================================ --- require: - cookstyle/chefstyle AllCops: TargetRubyVersion: 3.1 Include: - "**/*.rb" Exclude: - "vendor/**/*" - "spec/**/*" ================================================ FILE: .tool-versions ================================================ ruby 3.4.8 ================================================ FILE: .yardopts ================================================ --readme README.md --markup markdown ================================================ FILE: CHANGELOG.md ================================================ # Change Log ## [3.22.3](https://github.com/test-kitchen/kitchen-ec2/compare/v3.22.2...v3.22.3) (2026-04-28) ### Bug Fixes * Corrected the Amazon Linux 2023 naming convention ([#659](https://github.com/test-kitchen/kitchen-ec2/issues/659)) ([8757f4c](https://github.com/test-kitchen/kitchen-ec2/commit/8757f4c447921dd8a107985427d150029c35ed75)) ## [3.22.2](https://github.com/test-kitchen/kitchen-ec2/compare/v3.22.1...v3.22.2) (2026-03-16) ### Bug Fixes * Add support for Windows Server 2025 ([#656](https://github.com/test-kitchen/kitchen-ec2/issues/656)) ([c3ec8d4](https://github.com/test-kitchen/kitchen-ec2/commit/c3ec8d4c6edb3a4921fa09bc1b3e75d3a53027e1)) ## [3.22.1](https://github.com/test-kitchen/kitchen-ec2/compare/v3.22.0...v3.22.1) (2026-01-22) ### Bug Fixes * bump tk dep <5 ([#652](https://github.com/test-kitchen/kitchen-ec2/issues/652)) ([2135e0e](https://github.com/test-kitchen/kitchen-ec2/commit/2135e0e17ed6893f928849c7fc747740f96f764c)) ## [3.22.0](https://github.com/test-kitchen/kitchen-ec2/compare/v3.21.0...v3.22.0) (2026-01-22) ### Features * Add AWS SSM Session Manager transport support ([#646](https://github.com/test-kitchen/kitchen-ec2/issues/646)) ([6b0fa6d](https://github.com/test-kitchen/kitchen-ec2/commit/6b0fa6d9f838249eb6f1f16c44906eb1bff84307)) ### Bug Fixes * Fix issue on failing create action ([#622](https://github.com/test-kitchen/kitchen-ec2/issues/622)) ([eb1d328](https://github.com/test-kitchen/kitchen-ec2/commit/eb1d328c2b56ec505ca7af4b244d82a3ba3ff175)) * Fixing cookstyle error ([1e319c8](https://github.com/test-kitchen/kitchen-ec2/commit/1e319c887755f606a6ec2d8989fb420a42a01cbf)) ## [3.21.0](https://github.com/test-kitchen/kitchen-ec2/compare/v3.20.0...v3.21.0) (2025-09-09) ### Features * Added AWS EC2 Instance Connect support ([#640](https://github.com/test-kitchen/kitchen-ec2/issues/640)) ([241ce70](https://github.com/test-kitchen/kitchen-ec2/commit/241ce70fd4998db3fe9245e8c5f2b06fb40e2d09)) ## [3.20.0](https://github.com/test-kitchen/kitchen-ec2/compare/v3.19.1...v3.20.0) (2025-06-15) ### Features * add support for IPv6 ([#623](https://github.com/test-kitchen/kitchen-ec2/issues/623)) ([0577c59](https://github.com/test-kitchen/kitchen-ec2/commit/0577c59fec43dfdb7e7f452ee0001ff699135422)) ### Bug Fixes * Fix tests on Ruby 3.3 ([#634](https://github.com/test-kitchen/kitchen-ec2/issues/634)) ([4b3b524](https://github.com/test-kitchen/kitchen-ec2/commit/4b3b524f2d0f1080f629e88dde5d48309d392d40)) ## [3.19.1](https://github.com/test-kitchen/kitchen-ec2/compare/v3.19.0...v3.19.1) (2025-06-08) ### Bug Fixes * Update CentOS for username change on 9+ ([#631](https://github.com/test-kitchen/kitchen-ec2/issues/631)) ([471e027](https://github.com/test-kitchen/kitchen-ec2/commit/471e027b052a20400e6142aa74c907902d76c0d8)), closes [#630](https://github.com/test-kitchen/kitchen-ec2/issues/630) ## [3.19.0](https://github.com/test-kitchen/kitchen-ec2/compare/v3.18.0...v3.19.0) (2024-06-21) ### Features * Bump Ruby version to 3.1 ([#618](https://github.com/test-kitchen/kitchen-ec2/issues/618)) ([9645154](https://github.com/test-kitchen/kitchen-ec2/commit/9645154606fb23430879d5bb01f748a6ca45546b)) ### Bug Fixes * release please configs ([#627](https://github.com/test-kitchen/kitchen-ec2/issues/627)) ([3fdc119](https://github.com/test-kitchen/kitchen-ec2/commit/3fdc1194114803d730e1998ae3ba6ef74ebbedba)) ## [3.18.0](https://github.com/test-kitchen/kitchen-ec2/compare/v3.17.1...v3.18.0) (2023-11-28) ### Features * Implements placement options and license specifications ([#607](https://github.com/test-kitchen/kitchen-ec2/issues/607)) ([9a269b4](https://github.com/test-kitchen/kitchen-ec2/commit/9a269b45d3886be77df47fec146d6cdcb9f28d1c)) * Implements placement options and license specifications ([#615](https://github.com/test-kitchen/kitchen-ec2/issues/615)) ([10f0232](https://github.com/test-kitchen/kitchen-ec2/commit/10f02328571ef520bca8311efa2f54561ccb6b34)) ## [3.17.1](https://github.com/test-kitchen/kitchen-ec2/compare/v3.17.0...v3.17.1) (2023-11-27) ### Bug Fixes * Release ([b58158f](https://github.com/test-kitchen/kitchen-ec2/commit/b58158fa2693e581a9f1f5dbdbe7badb12536129)) ## [v3.17.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.17.0) (2023-06-14) - Add support for Rocky and AlmaLinux [#602](https://github.com/test-kitchen/kitchen-ec2/pull/602) ([@bjakauppila](https://github.com/jakauppila)) - Ruby 3 compatibility for RSpec suite [#603](https://github.com/test-kitchen/kitchen-ec2/pull/603) ([@RulerOf](https://github.com/RulerOf)) ## [v3.16.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.16.0) (2023-03-16) - Add support for Amazon Linux 2023 [#600](https://github.com/test-kitchen/kitchen-ec2/pull/600) ([@bjakauppila](https://github.com/jakauppila)) - Remove support for EOL Ruby 2.6 ([@tas50](https://github.com/tas50)) ## [v3.15.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.15.0) (2022-12-13) - Add support for specifying the SSH key type to be automatically generated [#583](https://github.com/test-kitchen/kitchen-ec2/pull/583) ([@bdwyertech](https://github.com/bdwyertech)) ## [v3.14.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.14.0) (2022-12-01) - Support for dedicated hosts [#592](https://github.com/test-kitchen/kitchen-ec2/pull/592) ([@tecracer-theinen](https://github.com/tecracer-theinen)) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.13.0..v3.14.0) ## [v3.13.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.13.0) (2022-05-30) - Added support for metadata_options [#573](https://github.com/test-kitchen/kitchen-ec2/pull/573) ([@bdwyertech](https://github.com/bdwyertech)) - Improve speed of readiness detection for Windows instances [#582](https://github.com/test-kitchen/kitchen-ec2/pull/582) ([@jakauppila](https://github.com/jakauppila)) - Updated the README to point to kitchen.ci [#577](https://github.com/test-kitchen/kitchen-ec2/pull/577) ([@kasif-adnan](https://github.com/kasif-adnan)) - Github workflow updates [#579](https://github.com/test-kitchen/kitchen-ec2/pull/579), [#584](https://github.com/test-kitchen/kitchen-ec2/pull/584) ([@kasif-adnan](https://github.com/kasif-adnan)) - Chefstyle linting and version updates [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.12.0..v3.13.0) ## [v3.12.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.12.0) (2021-12-20) - Adds support for defining multiple tags for subnet_filter [#570](https://github.com/test-kitchen/kitchen-ec2/pull/570) ([@jakauppila](https://github.com/jakauppila)) - Ensure instance is terminated if a failure occurs during creation [#570](https://github.com/test-kitchen/kitchen-ec2/pull/570) ([@jakauppila](https://github.com/jakauppila)) ## [v3.11.1](https://github.com/test-kitchen/kitchen-ec2/tree/v3.11.1) (2021-11-11) - Resolve deprecation warnings from the AWS SDK during execution [#567](https://github.com/test-kitchen/kitchen-ec2/pull/567) ([kasif-adnan](https://github.com/kasif-adnan)) ## [v3.11.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.11.0) (2021-11-02) - Added support for Windows 2022 [#557](https://github.com/test-kitchen/kitchen-ec2/pull/557) ([bdwyertech](https://github.com/bdwyertech)) - Added support for finding vendor images on Debian 10 and later ([tas50](https://github.com/tas50)) - Removed support for EOL Ruby 2.5 ([tas50](https://github.com/tas50)) ## [v3.10.1](https://github.com/test-kitchen/kitchen-ec2/tree/v3.10.1) (2021-10-28) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.10.0..v3.10.1) - Don't wait the full 300 seconds during `kitchen destroy` if the instance was deleted outside of Test Kitchen. ## [v3.10.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.10.0) (2021-07-02) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.9.0..v3.10.0) - Allow specifying Elastic Network Interface ID with a new `elastic_network_interface_id` configuration option. See the readme for additional details - Support Test Kitchen 3.0 - Improved the error message when an AMI ID cannot be found ## [v3.9.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.9.0) (2021-04-09) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.8.0..v3.9.0) - Require Ruby 2.5 + misc test cleanup [#533](https://github.com/test-kitchen/kitchen-ec2/pull/533) ([tas50](https://github.com/tas50)) - Update `delete_on_termination` to be true by default so we properly cleanup EBS volumes on RHEL systems [#539](https://github.com/test-kitchen/kitchen-ec2/pull/539) ([i5pranay93](https://github.com/i5pranay93)) - Add support for GP3 EBS volume types [#525](https://github.com/test-kitchen/kitchen-ec2/pull/525) ([bdwyertech](https://github.com/bdwyertech)) ## [v3.8.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.8.0) (2020-10-14) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.7.2..v3.8.0) - Allow multiple ip addresses to be specified when creating a security group [#509](https://github.com/test-kitchen/kitchen-ec2/pull/509) ([trainsushi](https://github.com/trainsushi)) - Use defaults when creating spot instances - fixes block_duration_minutes [#512](https://github.com/test-kitchen/kitchen-ec2/pull/512) ([clintoncwolfe](https://github.com/clintoncwolfe)) ## [v3.7.2](https://github.com/test-kitchen/kitchen-ec2/tree/v3.7.2) (2020-09-29) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.7.1..v3.7.2) - Prefer non-Beta RHEL AMIs in search [#506](https://github.com/test-kitchen/kitchen-ec2/pull/506) ([clintoncwolfe](https://github.com/clintoncwolfe)) - Minor performance optimization to subnet determination [#514](https://github.com/test-kitchen/kitchen-ec2/pull/514) ([clintoncwolfe](https://github.com/clintoncwolfe)) - Optimize our requires [#510](https://github.com/test-kitchen/kitchen-ec2/pull/510) ([tas50](https://github.com/tas50)) - Use match? instead of =~ to reduce memory usage [#508](https://github.com/test-kitchen/kitchen-ec2/pull/508) ([tas50](https://github.com/tas50)) - Document missing properties [#504](https://github.com/test-kitchen/kitchen-ec2/pull/504) ([mbaitelman](https://github.com/mbaitelman)) ## [v3.7.1](https://github.com/test-kitchen/kitchen-ec2/tree/v3.7.1) (2020-07-13) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.7.0..v3.7.1) - Improvements to CentOS Image search [#502](https://github.com/test-kitchen/kitchen-ec2/pull/502) ([clintoncwolfe](https://github.com/clintoncwolfe)) - Spot Instances - Cascading Subnet Filter Support [#499](https://github.com/test-kitchen/kitchen-ec2/pull/499) ([bdwyertech](https://github.com/bdwyertech)) - Remove excon and multi-json deps [#500](https://github.com/test-kitchen/kitchen-ec2/pull/500) ([tas50](https://github.com/tas50)) ## [v3.7.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.7.0) (2020-07-02) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.6.0..v3.7.0) - Tag on-demand instances and volumes at creation time [#496](https://github.com/test-kitchen/kitchen-ec2/pull/496) ([clintoncwolfe](https://github.com/clintoncwolfe)) ## [v3.6.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.6.0) (2020-05-17) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.5.0..v3.6.0) - Remove support for EOL Ruby 2.3 [#491](https://github.com/test-kitchen/kitchen-ec2/pull/491) ([tas50](https://github.com/tas50)) - Make Debian 10 the Debian default [#492](https://github.com/test-kitchen/kitchen-ec2/pull/492) ([tas50](https://github.com/tas50)) ## [v3.5.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.5.0) (2020-05-06) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.4.0..v3.5.0) - Select the least-populated subnet if we have multiple matches. This should help to distribute the test-kitchen load more evenly across multi-az VPC's while maintaining full backward compatibility. [\#489](https://github.com/test-kitchen/kitchen-ec2/pull/489) ([bdwyertech](https://github.com/bdwyertech)) - Readme example cleanup [\#484](https://github.com/test-kitchen/kitchen-ec2/pull/484) ([arothian](https://github.com/arothian)) ## [v3.4.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.4.0) (2020-03-18) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.3.0..v3.4.0) - Don't crash upon destroy if instance is already dead [\#482](https://github.com/test-kitchen/kitchen-ec2/pull/482) ([kamaradclimber](https://github.com/kamaradclimber)) ## [v3.3.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.3.0) (2020-01-20) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.2.0..v3.3.0) - Ignore case when checking if the instance provisioner is Chef [\#474](https://github.com/test-kitchen/kitchen-ec2/pull/474) ([slapvanilla](https://github.com/slapvanilla)) - Enhancements: Security Group Search & Spot Instance Provisioning [\#470](https://github.com/test-kitchen/kitchen-ec2/pull/470) ([bdwyertech](https://github.com/bdwyertech)) - Update chefstyle requirement from = 0.13.3 to = 0.14.0 [\#472](https://github.com/test-kitchen/kitchen-ec2/pull/472) ([tas50](https://github.com/tas50)) - Use require_relative instead of require [\#478](https://github.com/test-kitchen/kitchen-ec2/pull/478) ([tas50](https://github.com/tas50)) ## [v3.2.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.2.0) (2019-09-17) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.1.0..v3.2.0) - Allow for retryable 3.0 [\#466](https://github.com/test-kitchen/kitchen-ec2/pull/466) ([tas50](https://github.com/tas50)) - Update Chefstyle to 0.13.3 [\#465](https://github.com/test-kitchen/kitchen-ec2/pull/465) ([tas50](https://github.com/tas50)) - Adds Windows Server 2019 \(and tests\) [\#462](https://github.com/test-kitchen/kitchen-ec2/pull/462) ([mbaitelman](https://github.com/mbaitelman)) - \#394: Check subnet\_filter as well when creating security group [\#413](https://github.com/test-kitchen/kitchen-ec2/pull/413) ([llibicpep](https://github.com/llibicpep)) ## [v3.1.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.1.0) (2019-08-07) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.0.1..v3.1.0) - Resolve additional deprecation warnings from the new aws-sdk-v3 dependency. Thanks [@Annih](https://github.com/Annih) - Add support for SSH through Session Manager. Thanks [@awiddersheim](https://github.com/awiddersheim) - Adds support for searching for multiple security groups, as well as searching by group name. Thanks [@bdwyertech](https://github.com/bdwyertech) - Allow asking for multiple instance types and subnets for spot pricing. Thanks [@vmiszczak-teads](https://github.com/vmiszczak-teads) ## [v3.0.1](https://github.com/test-kitchen/kitchen-ec2/tree/v3.0.1) (2019-05-08) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v3.0.0..v3.0.1) - Resolve deprecation warnings from the new aws-sdk-v3 dependency ## [v3.0.0](https://github.com/test-kitchen/kitchen-ec2/tree/v3.0.0) (2019-05-01) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.4.0..v3.0.0) - Switch from the monolithic aws-sdk-v2 to the just aws-sdk-ec2 aka aws-sdk-v3. This greatly reduces the number of dependencies necessary for this plugin, but is a major change that makes it incompatible with older released of ChefDK that require aws-sdk-v2. - Require Ruby 2.3 or later as Ruby 2.2 is now EOL - Loosen the dependency on Test Kitchen to allow this plugin to work with Test Kitchen 2.0 - Fix hostname detection to not fail when the system doesn't have a public IP. Thanks [@niekrasp](https://github.com/niekrasp) - Added a new `security_group_cidr_ip` config for specifying IP CIDRs in the security group. Defaults to 0.0.0.0/0. Thanks [@dpattmann](https://github.com/dpattmann) - Support providing full Debian versions like 9.6 instead of just the major release like 9 - Ensure tags keys are strings as expected by AWS SDK. Thanks [@Annih](https://github.com/Annih) - Leverage quadratic backoff retry on instance creation throttling. Thanks [@Annih](https://github.com/Annih) - Honor AWS_PROFILE if present. Thanks [@bdwyertech](https://github.com/bdwyertech) ## [v2.4.0](https://github.com/test-kitchen/kitchen-ec2/tree/v2.4.0) (2018-12-20) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.3.4..v2.4.0) - Don't ship spec files in the gem artifact - Support Amazon Linux 2.0 image searching. Use the platform 'amazon2' - Support Windows Server 1709 and 1803 image searching ## [v2.3.4](https://github.com/test-kitchen/kitchen-ec2/tree/v2.3.4) (2018-12-04) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.3.3...v2.3.4) - Don't ship the changelog in the gem ## [v2.3.3](https://github.com/test-kitchen/kitchen-ec2/tree/v2.3.3) (2018-11-28) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.3.2...v2.3.3) **Merged pull requests:** - Adding support for arm64 architecture [\#433] ## [v2.3.2](https://github.com/test-kitchen/kitchen-ec2/tree/v2.3.2) (2018-11-28) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.3.1...v2.3.2) **Fixed Bugs:** - fix x86_64 architecture default for image search (fixes new arm64 arch appearing instead) [\#432] ## [v2.3.1](https://github.com/test-kitchen/kitchen-ec2/tree/v2.3.1) (2018-10-19) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.3.0...v2.3.1) **Fixed Bugs:** - windows2012-r2 hanging on userdata.ps1 in kitchen-ec2 2.3.0 [\#424] ## [v2.3.0](https://github.com/test-kitchen/kitchen-ec2/tree/v2.3.0) (2018-10-05) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.2.2...v2.3.0) - Add port 3389 (RDP) to the automatically generated security group - Fix logfile creation on Windows to not fail if the directory doesn't exist - The gem no longer ships with test deps so we can slim the install size ## [v2.2.2](https://github.com/test-kitchen/kitchen-ec2/tree/v2.2.2) (2018-06-11) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.2.1...v2.2.2) **Fixed bugs:** - Kitchen failure when adding spot\_price [\#328](https://github.com/test-kitchen/kitchen-ec2/issues/328) **Closed issues:** - image\_id: required [\#397](https://github.com/test-kitchen/kitchen-ec2/issues/397) - kitchen-ec2 ssh port [\#396](https://github.com/test-kitchen/kitchen-ec2/issues/396) - Provide option to terminate after "X" minutes [\#395](https://github.com/test-kitchen/kitchen-ec2/issues/395) - Explicitly support usage w/o manual or autoconfiguration of aws\_ssh\_key\_id [\#391](https://github.com/test-kitchen/kitchen-ec2/issues/391) **Merged pull requests:** - Fix dynamic key creation [\#400](https://github.com/test-kitchen/kitchen-ec2/pull/400) ([bdwyertech](https://github.com/bdwyertech)) - allow AWS-managed ssh key pairs to be disabled [\#392](https://github.com/test-kitchen/kitchen-ec2/pull/392) ([cheeseplus](https://github.com/cheeseplus)) ## [v2.2.1](https://github.com/test-kitchen/kitchen-ec2/tree/v2.2.1) (2018-02-12) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.2.0...v2.2.1) **Fixed bugs:** - Fix `undefined` error when Windows AMIs don't include "windows" in name [\#322](https://github.com/test-kitchen/kitchen-ec2/issues/322) [\#324](https://github.com/test-kitchen/kitchen-ec2/pull/324) ([BenLiyanage](https://github.com/BenLiyanage)) - Fix error behavior when security\_group\_filter is set but no security group found for those tags [\#386](https://github.com/test-kitchen/kitchen-ec2/pull/386) ([dpattmann](https://github.com/dpattmann)) - Don't create security group if security\_group\_filter is set [\#385](https://github.com/test-kitchen/kitchen-ec2/pull/385) ([dpattmann](https://github.com/dpattmann)) ## [v2.2.0](https://github.com/test-kitchen/kitchen-ec2/tree/v2.2.0) (2018-01-27) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.1.0...v2.2.0) - When config validation fails we now show you just the error message instead of the full stack trace with a buried error message - Removed the username logic for FreeBSD < 9.1 as those releases are EOL - Add support for Debian 10/11 so we'll support them as soon as they're released - Added support for the 'host' tenancy value - Added proper config validation for tenancy instead of silently skipping bad data - Properly handle Integers in tags instead of failing the run - Properly handle nil values in tags instead of failing the run - Add validation to make sure the tags are passed as a single hash instead of an array of each tag - Update our Yard dev dependency to make sure we have 0.9.11+ to avoid a CVE in earlier releases - Update links in docs and distros in the examples - Removed Rubocop comments that weren't necessary from the code ## [v2.1.0](https://github.com/test-kitchen/kitchen-ec2/tree/v2.1.0) (2018-01-27) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v2.0.0...v2.1.0) **Merged pull requests:** - Only create Ohai hint when provisioner is `/chef/` [\#366](https://github.com/test-kitchen/kitchen-ec2/pull/366) ([cheeseplus](https://github.com/cheeseplus)) - Automatically create a security group and key pair if needed. [\#362](https://github.com/test-kitchen/kitchen-ec2/pull/362) ([coderanger](https://github.com/coderanger)) ## [v2.0.0](https://github.com/test-kitchen/kitchen-ec2/tree/v2.0.0) (2017-12-08) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.4.0...v2.0.0) ### Improvements - Clean up original Authentication; Rely on SDK for Chain. [\#353](https://github.com/test-kitchen/kitchen-ec2/pull/353) ([rhyas](https://github.com/rhyas)) - Use quadratic backoff when encountering RequestLimit errors [\#320](https://github.com/test-kitchen/kitchen-ec2/pull/320) ([kamaradclimber](https://github.com/kamaradclimber)) ## [v1.4.0](https://github.com/test-kitchen/kitchen-ec2/tree/v1.4.0) (2017-11-29) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.3.2...v1.4.0) ### Improvements - Explicitly initialise secondary disks on windows 2016 [\#352](https://github.com/test-kitchen/kitchen-ec2/pull/352) ([rlaveycal](https://github.com/rlaveycal)) - Fix windows user\_data log file [\#350](https://github.com/test-kitchen/kitchen-ec2/pull/350) ([rlaveycal](https://github.com/rlaveycal)) - Set LocalAccountTokenFilterPolicy to allow powershell remoting from local accounts [\#348](https://github.com/test-kitchen/kitchen-ec2/pull/348) ([Sam-Martin](https://github.com/Sam-Martin)) - Add EC2 hostname when printing ready message [\#346](https://github.com/test-kitchen/kitchen-ec2/pull/346) ([pierrecdn](https://github.com/pierrecdn)) - Fix for issue with instance-store backed instance \(issue \#318\) [\#343](https://github.com/test-kitchen/kitchen-ec2/pull/343) ([naunga](https://github.com/naunga)) - Handle nulls/binary text in user data so it supports gzip [\#338](https://github.com/test-kitchen/kitchen-ec2/pull/338) ([brodygov](https://github.com/brodygov)) - This updates the documentation [\#337](https://github.com/test-kitchen/kitchen-ec2/pull/337) ([stiller-leser](https://github.com/stiller-leser)) - Add support for Debian Stretch [\#327](https://github.com/test-kitchen/kitchen-ec2/pull/327) ([RoboticCheese](https://github.com/RoboticCheese)) - Add support for Amazon Linux [\#321](https://github.com/test-kitchen/kitchen-ec2/pull/321) ([steven-burns](https://github.com/steven-burns)) - modernize winrm setup and fix for 2008r2 [\#304](https://github.com/test-kitchen/kitchen-ec2/pull/304) ([mwrock](https://github.com/mwrock)) - Updated readme based on issue 300 [\#302](https://github.com/test-kitchen/kitchen-ec2/pull/302) ([pgporada](https://github.com/pgporada)) - Use Chefstyle and require Ruby 2.2.2 [\#301](https://github.com/test-kitchen/kitchen-ec2/pull/301) ([tas50](https://github.com/tas50)) ## [v1.3.2](https://github.com/test-kitchen/kitchen-ec2/tree/v1.3.2) (2017-02-24) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.3.1...v1.3.2) **Improvements:** - Don't try to set tags if there aren't any. [\#298](https://github.com/test-kitchen/kitchen-ec2/pull/298) ([coderanger](https://github.com/coderanger)) ## [v1.3.1](https://github.com/test-kitchen/kitchen-ec2/tree/v1.3.1) (2017-02-16) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.3.0...v1.3.1) **Closed issues:** - Shared AWS credentials file being ignored. [\#295](https://github.com/test-kitchen/kitchen-ec2/issues/295) - Missing AMI generates Nil::NilClass error [\#284](https://github.com/test-kitchen/kitchen-ec2/issues/284) - `kitchen converge` failing - not prioritizing env vars over ~/.aws/credentials [\#258](https://github.com/test-kitchen/kitchen-ec2/issues/258) **Merged pull requests:** - reinstate default shared creds option [\#296](https://github.com/test-kitchen/kitchen-ec2/pull/296) ([davidcpell](https://github.com/davidcpell)) ## [v1.3.0](https://github.com/test-kitchen/kitchen-ec2/tree/v1.3.0) (2017-02-11) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.2.0...v1.3.0) **Implemented Enhancements:** - Support Windows 2016 [\#291](https://github.com/test-kitchen/kitchen-ec2/pull/291) ([gdavison](https://github.com/gdavison)) - Add expiration to spot requests [\#285](https://github.com/test-kitchen/kitchen-ec2/pull/285) ([alanbrent](https://github.com/alanbrent)) - Don't break if we're using a custom "platform" AMI [\#273](https://github.com/test-kitchen/kitchen-ec2/pull/273) ([hynd](https://github.com/hynd)) - Propagate tags to volumes [\#260](https://github.com/test-kitchen/kitchen-ec2/pull/260) ([mrbobbytables](https://github.com/mrbobbytables)) - In the client, only source creds from the shared file when necessary [\#259](https://github.com/test-kitchen/kitchen-ec2/pull/259) ([davidcpell](https://github.com/davidcpell)) - Add notes for AMI image name requirements [\#252](https://github.com/test-kitchen/kitchen-ec2/pull/252) ([freimer](https://github.com/freimer)) - Provide the option to set ssl\_peer\_verify to false [\#251](https://github.com/test-kitchen/kitchen-ec2/pull/251) ([mwrock](https://github.com/mwrock)) - Adding support for tenancy parameter in placement config. [\#235](https://github.com/test-kitchen/kitchen-ec2/pull/235) ([jcastillocano](https://github.com/jcastillocano)) - Lookup ID from tag [\#232](https://github.com/test-kitchen/kitchen-ec2/pull/232) ([dlukman](https://github.com/dlukman)) ## [v1.2.0](https://github.com/test-kitchen/kitchen-ec2/tree/v1.2.0) (2016-09-12) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.1.0...v1.2.0) **Fixed bugs:** - Turn on eager loading for AWS resources [\#255](https://github.com/test-kitchen/kitchen-ec2/pull/255) ([hfinucane](https://github.com/hfinucane)) **Merged pull requests:** - Add optional config for shutdown\_behavior [\#274](https://github.com/test-kitchen/kitchen-ec2/pull/274) ([alexpop](https://github.com/alexpop)) - pin rack to ~\> 1.0 [\#272](https://github.com/test-kitchen/kitchen-ec2/pull/272) ([mwrock](https://github.com/mwrock)) - Fix \#268 [\#269](https://github.com/test-kitchen/kitchen-ec2/pull/269) ([gasserk](https://github.com/gasserk)) - Allow PowerShell script execution [\#234](https://github.com/test-kitchen/kitchen-ec2/pull/234) ([dlukman](https://github.com/dlukman)) ## [v1.1.0](https://github.com/test-kitchen/kitchen-ec2/tree/v1.1.0) (2016-08-09) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.0.1...v1.1.0) **Implemented enhancements:** - Make tags optional for clients without IAM rights to CreateTags [\#257](https://github.com/test-kitchen/kitchen-ec2/pull/257) ([freimer](https://github.com/freimer)) **Fixed bugs:** - New transport.ssh\_key does not work in Travis, possibly elsewhere [\#203](https://github.com/test-kitchen/kitchen-ec2/issues/203) - not able to connect via winrm [\#175](https://github.com/test-kitchen/kitchen-ec2/issues/175) - Fix AWS Ruby SDK autoload for all time [\#270](https://github.com/test-kitchen/kitchen-ec2/pull/270) ([jkeiser](https://github.com/jkeiser)) **Closed issues:** - Do not require aws\_ssh\_key\_id in ec2.rb [\#268](https://github.com/test-kitchen/kitchen-ec2/issues/268) - Retrieve AMI IDs from the EC2 API [\#147](https://github.com/test-kitchen/kitchen-ec2/issues/147) ## [v1.0.1](https://github.com/test-kitchen/kitchen-ec2/tree/v1.0.1) (2016-07-20) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.0.0...v1.0.1) **Fixed bugs:** - Default AMIs for Windows not available [\#174](https://github.com/test-kitchen/kitchen-ec2/issues/174) - Fix autoload race in Aws::EC2::\* [\#264](https://github.com/test-kitchen/kitchen-ec2/pull/264) ([jkeiser](https://github.com/jkeiser)) ## [v1.0.0](https://github.com/test-kitchen/kitchen-ec2/tree/v1.0.0) (2016-03-03) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v1.0.0.beta.1...v1.0.0) **Merged pull requests:** - Use github\_changelog\_generator for changelog [\#231](https://github.com/test-kitchen/kitchen-ec2/pull/231) ([jkeiser](https://github.com/jkeiser)) - Rename price -\> spot\_price, fix rubocop [\#229](https://github.com/test-kitchen/kitchen-ec2/pull/229) ([jkeiser](https://github.com/jkeiser)) - support duration for spot instances [\#214](https://github.com/test-kitchen/kitchen-ec2/pull/214) ([wjordan](https://github.com/wjordan)) - Add support for looking up Private DNS Name for hostname [\#197](https://github.com/test-kitchen/kitchen-ec2/pull/197) ([mekf](https://github.com/mekf)) ## [v1.0.0.beta.1](https://github.com/test-kitchen/kitchen-ec2/tree/v1.0.0.beta.1) (2016-02-13) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.10.0...v1.0.0.beta.1) **Implemented enhancements:** - Slow file transference [\#93](https://github.com/test-kitchen/kitchen-ec2/issues/93) - Dynamically find default images for many platforms [\#221](https://github.com/test-kitchen/kitchen-ec2/pull/221) ([jkeiser](https://github.com/jkeiser)) - Query Ubuntu AMI IDs [\#169](https://github.com/test-kitchen/kitchen-ec2/pull/169) ([whiteley](https://github.com/whiteley)) **Fixed bugs:** - Improve error handling if kitchen instance is destroy out of band [\#210](https://github.com/test-kitchen/kitchen-ec2/issues/210) - SSH prompting password for an instance inside VPC [\#129](https://github.com/test-kitchen/kitchen-ec2/issues/129) - amis.json out of date [\#117](https://github.com/test-kitchen/kitchen-ec2/issues/117) - Fix sudo dependency. Fixes \#204 [\#219](https://github.com/test-kitchen/kitchen-ec2/pull/219) ([alexpop](https://github.com/alexpop)) - Use ubuntu user for Ubuntu 15.04 and 15.10 [\#196](https://github.com/test-kitchen/kitchen-ec2/pull/196) ([jaym](https://github.com/jaym)) - Adding better retry logic to creation, fixes \#179 \(hopefully\) [\#184](https://github.com/test-kitchen/kitchen-ec2/pull/184) ([tyler-ball](https://github.com/tyler-ball)) - Add support for looking up AMIs with the EC2 API [\#177](https://github.com/test-kitchen/kitchen-ec2/pull/177) ([zl4bv](https://github.com/zl4bv)) - Trying :instance\_running check before tagging [\#171](https://github.com/test-kitchen/kitchen-ec2/pull/171) ([tyler-ball](https://github.com/tyler-ball)) **Closed issues:** - Requesting to include this plug-in in ChefDK [\#218](https://github.com/test-kitchen/kitchen-ec2/issues/218) - Can't ssh to instance after it's created [\#217](https://github.com/test-kitchen/kitchen-ec2/issues/217) - No installation instructions [\#216](https://github.com/test-kitchen/kitchen-ec2/issues/216) - availability\_zone is always b [\#215](https://github.com/test-kitchen/kitchen-ec2/issues/215) - Windows create fails fetching password [\#211](https://github.com/test-kitchen/kitchen-ec2/issues/211) - Offering to help maintain this repo [\#209](https://github.com/test-kitchen/kitchen-ec2/issues/209) - Support for HVM EC2 instances [\#205](https://github.com/test-kitchen/kitchen-ec2/issues/205) - Installation fails due to sudo dependency in test-kitchen [\#204](https://github.com/test-kitchen/kitchen-ec2/issues/204) - Not all AMIs in amis.json are public. [\#202](https://github.com/test-kitchen/kitchen-ec2/issues/202) - connection\_retries doesn't seem to work? [\#200](https://github.com/test-kitchen/kitchen-ec2/issues/200) - kitchen converge needs to be run 2-3 times to work with stock Windows 2012r2 AMI ami-dfccd1ef [\#198](https://github.com/test-kitchen/kitchen-ec2/issues/198) - Unable to assign a name to an ec2 instance [\#194](https://github.com/test-kitchen/kitchen-ec2/issues/194) - Administrator password not being retrieved on Windows 2008 R2 [\#192](https://github.com/test-kitchen/kitchen-ec2/issues/192) - Removing Default Storage when running Kitchen Destroy [\#188](https://github.com/test-kitchen/kitchen-ec2/issues/188) - Test Kitchen issues on EC2 using RHEL platform? [\#181](https://github.com/test-kitchen/kitchen-ec2/issues/181) - Failure for numeric key name [\#178](https://github.com/test-kitchen/kitchen-ec2/issues/178) - Issues under high concurrency [\#176](https://github.com/test-kitchen/kitchen-ec2/issues/176) - SSH Connection Expiring Upon Instance Creation [\#173](https://github.com/test-kitchen/kitchen-ec2/issues/173) - Throttle requests to EC2 API [\#170](https://github.com/test-kitchen/kitchen-ec2/issues/170) - missing aws\_secret\_access\_key causes quiet timeout [\#155](https://github.com/test-kitchen/kitchen-ec2/issues/155) **Merged pull requests:** - Bump revision to 1.0.0.beta.1 [\#224](https://github.com/test-kitchen/kitchen-ec2/pull/224) ([jkeiser](https://github.com/jkeiser)) - Update travis ruby versions and update badges [\#213](https://github.com/test-kitchen/kitchen-ec2/pull/213) ([tas50](https://github.com/tas50)) - Allow configuring retry\_limit in Aws.config [\#208](https://github.com/test-kitchen/kitchen-ec2/pull/208) ([jlyheden](https://github.com/jlyheden)) - Default instance type change, and Ubuntu AMI search options to match [\#207](https://github.com/test-kitchen/kitchen-ec2/pull/207) ([vancluever](https://github.com/vancluever)) - Add support for CentOS 7 [\#199](https://github.com/test-kitchen/kitchen-ec2/pull/199) ([proffalken](https://github.com/proffalken)) - Update CHANGELOG.md [\#183](https://github.com/test-kitchen/kitchen-ec2/pull/183) ([failshell](https://github.com/failshell)) ## [v0.10.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.10.0) (2015-06-24) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.10.0.rc.1...v0.10.0) **Fixed bugs:** - ebs\_volume\_type missing parameters when set to 'io1' [\#157](https://github.com/test-kitchen/kitchen-ec2/issues/157) - setting http\_proxy causes no\_proxy to be ignored [\#156](https://github.com/test-kitchen/kitchen-ec2/issues/156) - transport configuration options do not work [\#145](https://github.com/test-kitchen/kitchen-ec2/issues/145) - expected params\[:network\_interfaces\]\[0\]\[:groups\] to be an array [\#144](https://github.com/test-kitchen/kitchen-ec2/issues/144) - Premature timeout when waiting for WinRM for be ready [\#132](https://github.com/test-kitchen/kitchen-ec2/issues/132) - Allow `:security\_group\_ids` to accept a string value. [\#166](https://github.com/test-kitchen/kitchen-ec2/pull/166) ([fnichol](https://github.com/fnichol)) - Adding block\_device\_mapping iops parameter, fixes \#157 [\#165](https://github.com/test-kitchen/kitchen-ec2/pull/165) ([tyler-ball](https://github.com/tyler-ball)) - Fix 'invalid char in json text' error [\#161](https://github.com/test-kitchen/kitchen-ec2/pull/161) ([zl4bv](https://github.com/zl4bv)) - Remove useless log message [\#158](https://github.com/test-kitchen/kitchen-ec2/pull/158) ([ustuehler](https://github.com/ustuehler)) - Remove useless log message [\#158](https://github.com/test-kitchen/kitchen-ec2/pull/158) ([ustuehler](https://github.com/ustuehler)) **Closed issues:** - efdk bundle update [\#163](https://github.com/test-kitchen/kitchen-ec2/issues/163) **Merged pull requests:** - reference to required IAM settings [\#160](https://github.com/test-kitchen/kitchen-ec2/pull/160) ([gmiranda23](https://github.com/gmiranda23)) ## [v0.10.0.rc.1](https://github.com/test-kitchen/kitchen-ec2/tree/v0.10.0.rc.1) (2015-06-19) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.10.0.rc.0...v0.10.0.rc.1) ## [v0.10.0.rc.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.10.0.rc.0) (2015-06-18) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.9.5...v0.10.0.rc.0) **Fixed bugs:** - block device examples updated [\#136](https://github.com/test-kitchen/kitchen-ec2/pull/136) ([gmiranda23](https://github.com/gmiranda23)) **Closed issues:** - Documentation - IAM policy document [\#159](https://github.com/test-kitchen/kitchen-ec2/issues/159) - kitchen-ec2 version 0.9.4 ssh transport is broken [\#154](https://github.com/test-kitchen/kitchen-ec2/issues/154) - Setting multiple non-default transport usernames per platform will soon be broken [\#153](https://github.com/test-kitchen/kitchen-ec2/issues/153) **Merged pull requests:** - Pulling together existing PRs for windows support [\#150](https://github.com/test-kitchen/kitchen-ec2/pull/150) ([tyler-ball](https://github.com/tyler-ball)) ## [v0.9.5](https://github.com/test-kitchen/kitchen-ec2/tree/v0.9.5) (2015-06-08) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.9.4...v0.9.5) **Fixed bugs:** - You broke Chef's Travis CI tests =\) [\#148](https://github.com/test-kitchen/kitchen-ec2/issues/148) **Closed issues:** - Race condition logging into RHEL/CentOS instances [\#149](https://github.com/test-kitchen/kitchen-ec2/issues/149) **Merged pull requests:** - Query correct instance object for hostname fixes \#148 [\#151](https://github.com/test-kitchen/kitchen-ec2/pull/151) ([tyler-ball](https://github.com/tyler-ball)) ## [v0.9.4](https://github.com/test-kitchen/kitchen-ec2/tree/v0.9.4) (2015-06-03) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.9.3...v0.9.4) **Fixed bugs:** - undefined local variable or method `logger' on kitchen create [\#142](https://github.com/test-kitchen/kitchen-ec2/issues/142) - Kitchen setup on Centos6.4 fails initial ssh auth with valid credentials [\#137](https://github.com/test-kitchen/kitchen-ec2/issues/137) - TK Can't Connect to EC2 Instance via SSH [\#135](https://github.com/test-kitchen/kitchen-ec2/issues/135) - Providing logger to instance\_generator, fixes \#142 [\#146](https://github.com/test-kitchen/kitchen-ec2/pull/146) ([tyler-ball](https://github.com/tyler-ball)) **Closed issues:** - kitchen destroy bombs trying to destroy non-existent instances [\#143](https://github.com/test-kitchen/kitchen-ec2/issues/143) - EC2-Instance terminates while TK waits on it to become ready [\#130](https://github.com/test-kitchen/kitchen-ec2/issues/130) **Merged pull requests:** - \#66: changed \[driver\_usage\] link to point to GitHub [\#141](https://github.com/test-kitchen/kitchen-ec2/pull/141) ([dsavinkov](https://github.com/dsavinkov)) ## [v0.9.3](https://github.com/test-kitchen/kitchen-ec2/tree/v0.9.3) (2015-05-29) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.9.2...v0.9.3) **Fixed bugs:** - Error trying to tag instance before it exists [\#138](https://github.com/test-kitchen/kitchen-ec2/issues/138) - \[Network interfaces and an instance-level security groups may not be specified on the same request\] [\#127](https://github.com/test-kitchen/kitchen-ec2/issues/127) **Closed issues:** - Failure to specify username leads to confusing error message [\#113](https://github.com/test-kitchen/kitchen-ec2/issues/113) - Kitchen attempts to log in before sshd is ready [\#85](https://github.com/test-kitchen/kitchen-ec2/issues/85) **Merged pull requests:** - Adding an existence check before tagging server [\#140](https://github.com/test-kitchen/kitchen-ec2/pull/140) ([tyler-ball](https://github.com/tyler-ball)) ## [v0.9.2](https://github.com/test-kitchen/kitchen-ec2/tree/v0.9.2) (2015-05-27) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.9.1...v0.9.2) **Fixed bugs:** - Support for proxy? [\#126](https://github.com/test-kitchen/kitchen-ec2/issues/126) - Support for proxy? [\#126](https://github.com/test-kitchen/kitchen-ec2/issues/126) - User Data content should be base64 encoded when passed to aws sdk [\#121](https://github.com/test-kitchen/kitchen-ec2/issues/121) **Closed issues:** - kitchen-ec2 fails when setting associate\_public\_ip: false [\#106](https://github.com/test-kitchen/kitchen-ec2/issues/106) **Merged pull requests:** - Adding proxy support that was present in Fog back [\#131](https://github.com/test-kitchen/kitchen-ec2/pull/131) ([tyler-ball](https://github.com/tyler-ball)) - Fixing 2 regressions in 0.9.1 [\#128](https://github.com/test-kitchen/kitchen-ec2/pull/128) ([tyler-ball](https://github.com/tyler-ball)) ## [v0.9.1](https://github.com/test-kitchen/kitchen-ec2/tree/v0.9.1) (2015-05-21) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.9.0...v0.9.1) **Fixed bugs:** - hostname missing when waiting for ssh service in create action [\#122](https://github.com/test-kitchen/kitchen-ec2/issues/122) - ebs\_delete\_on\_termination is not working [\#91](https://github.com/test-kitchen/kitchen-ec2/issues/91) - Fixing error where aws returns DNS name as empty string [\#124](https://github.com/test-kitchen/kitchen-ec2/pull/124) ([tyler-ball](https://github.com/tyler-ball)) **Closed issues:** - Limited Permissions - Failed to complete \#create action: \[You are not authorized to perform this operation.\] [\#120](https://github.com/test-kitchen/kitchen-ec2/issues/120) - release 0.8.0 doesn't properly honor instance\_type [\#114](https://github.com/test-kitchen/kitchen-ec2/issues/114) - tag\_server: tag key needs to be cast to string [\#111](https://github.com/test-kitchen/kitchen-ec2/issues/111) - The specified wait\_for timeout \(600 seconds\) was exceeded [\#103](https://github.com/test-kitchen/kitchen-ec2/issues/103) - block\_device\_mappings setting is not optional [\#100](https://github.com/test-kitchen/kitchen-ec2/issues/100) - kitchen-ec2 - iam\_profile\_name fog not passing through [\#94](https://github.com/test-kitchen/kitchen-ec2/issues/94) - Unable to SSH into VPC Instance [\#77](https://github.com/test-kitchen/kitchen-ec2/issues/77) - Can't get a public IP [\#72](https://github.com/test-kitchen/kitchen-ec2/issues/72) - Why no releases since Feb? [\#65](https://github.com/test-kitchen/kitchen-ec2/issues/65) **Merged pull requests:** - Fixing :subnet\_id payload placement if :associate\_public\_ip is set [\#125](https://github.com/test-kitchen/kitchen-ec2/pull/125) ([tyler-ball](https://github.com/tyler-ball)) ## [v0.9.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.9.0) (2015-05-19) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.8.0...v0.9.0) **Implemented enhancements:** - Support HVM based virtualization [\#25](https://github.com/test-kitchen/kitchen-ec2/issues/25) - Support spot-instances [\#6](https://github.com/test-kitchen/kitchen-ec2/issues/6) **Fixed bugs:** - Might be leaving orphaned EBS volumes [\#30](https://github.com/test-kitchen/kitchen-ec2/issues/30) - `kitchen login` fails if ssh\_key is a relative path. [\#26](https://github.com/test-kitchen/kitchen-ec2/issues/26) - Fix security\_group\_ids parameter for spot requests [\#90](https://github.com/test-kitchen/kitchen-ec2/pull/90) ([gfloyd](https://github.com/gfloyd)) **Closed issues:** - Issue with amazon linux 32 bit and SCP failing \>\>\>\>\>\> Message: Failed to complete \#converge action: \[SCP did not finish successfully \(127\): \] [\#88](https://github.com/test-kitchen/kitchen-ec2/issues/88) - The plugin does not create /etc/chef/ohai/hints/ec2.json file [\#86](https://github.com/test-kitchen/kitchen-ec2/issues/86) - how do you pass user data to the instance? [\#79](https://github.com/test-kitchen/kitchen-ec2/issues/79) - Can't find how to set EBS Volume Size [\#71](https://github.com/test-kitchen/kitchen-ec2/issues/71) - Instance created but nothing happens from there [\#62](https://github.com/test-kitchen/kitchen-ec2/issues/62) - Use IAM role to authenticate with AWS [\#55](https://github.com/test-kitchen/kitchen-ec2/issues/55) - iam\_profile\_name not being added to ec2 [\#54](https://github.com/test-kitchen/kitchen-ec2/issues/54) - it always invokes tests as root [\#52](https://github.com/test-kitchen/kitchen-ec2/issues/52) - Failing authentication for some larger instances. [\#51](https://github.com/test-kitchen/kitchen-ec2/issues/51) - allow to hide aws keys from kitchen.yml [\#50](https://github.com/test-kitchen/kitchen-ec2/issues/50) - Configuration option for naming EC2 instances? [\#48](https://github.com/test-kitchen/kitchen-ec2/issues/48) - Ohai attribute node\[:ec2\] is nil [\#47](https://github.com/test-kitchen/kitchen-ec2/issues/47) - Resolving dependencies on ec2 instead upload resolved cookbooks to ec2 [\#40](https://github.com/test-kitchen/kitchen-ec2/issues/40) - fails to connect to ec2 if ip/host is not in known\_hosts entry [\#38](https://github.com/test-kitchen/kitchen-ec2/issues/38) - doesn't invoke test while using ec2 driver [\#37](https://github.com/test-kitchen/kitchen-ec2/issues/37) - Default to IAM Credentials if aws\_access\_key\_id or aws\_secret\_access\_key Not Provided [\#19](https://github.com/test-kitchen/kitchen-ec2/issues/19) **Merged pull requests:** - Test Kitchen 1.4.0 has been released [\#112](https://github.com/test-kitchen/kitchen-ec2/pull/112) ([jaym](https://github.com/jaym)) - Adding test coverage [\#110](https://github.com/test-kitchen/kitchen-ec2/pull/110) ([tyler-ball](https://github.com/tyler-ball)) - Updating to depend on TK 1.4 [\#109](https://github.com/test-kitchen/kitchen-ec2/pull/109) ([tyler-ball](https://github.com/tyler-ball)) - Add explicit option for using iam profile for authentication [\#107](https://github.com/test-kitchen/kitchen-ec2/pull/107) ([JamesAwesome](https://github.com/JamesAwesome)) - Add support for IAM role credentials [\#104](https://github.com/test-kitchen/kitchen-ec2/pull/104) ([Igorshp](https://github.com/Igorshp)) - Fix the regression after changes in 23f4d945 [\#99](https://github.com/test-kitchen/kitchen-ec2/pull/99) ([mumoshu](https://github.com/mumoshu)) - New `block\_device\_mappings` config [\#98](https://github.com/test-kitchen/kitchen-ec2/pull/98) ([tyler-ball](https://github.com/tyler-ball)) - Fix connection to servers without a "public\_ip\_address" interface \(ie: VPC\) [\#97](https://github.com/test-kitchen/kitchen-ec2/pull/97) ([tyler-ball](https://github.com/tyler-ball)) - Updating documentation so first-time users have an easier time [\#92](https://github.com/test-kitchen/kitchen-ec2/pull/92) ([tyler-ball](https://github.com/tyler-ball)) - Added private\_ip\_address support. [\#84](https://github.com/test-kitchen/kitchen-ec2/pull/84) ([scarolan](https://github.com/scarolan)) - added user\_data for instance preparation [\#82](https://github.com/test-kitchen/kitchen-ec2/pull/82) ([sebbrandt87](https://github.com/sebbrandt87)) - Fix connection to servers without a "public\_ip\_address" interface \(ie: VPC\) [\#69](https://github.com/test-kitchen/kitchen-ec2/pull/69) ([chuckg](https://github.com/chuckg)) - Add Ubuntu 13.10 and 14.04 AMIs [\#63](https://github.com/test-kitchen/kitchen-ec2/pull/63) ([justincampbell](https://github.com/justincampbell)) - Added AWS\_SESSION\_TOKEN parameter to readme [\#60](https://github.com/test-kitchen/kitchen-ec2/pull/60) ([berniedurfee](https://github.com/berniedurfee)) - Customize ssh\_timeout and ssh\_retries [\#58](https://github.com/test-kitchen/kitchen-ec2/pull/58) ([ekrupnik](https://github.com/ekrupnik)) - Added .project to .gitignore file [\#57](https://github.com/test-kitchen/kitchen-ec2/pull/57) ([ekrupnik](https://github.com/ekrupnik)) - Add missing "a" to interface header [\#49](https://github.com/test-kitchen/kitchen-ec2/pull/49) ([eherot](https://github.com/eherot)) - Don't create multiple instances if "kitchen create" is called multiple t... [\#46](https://github.com/test-kitchen/kitchen-ec2/pull/46) ([anl](https://github.com/anl)) - Warn about $$$ [\#41](https://github.com/test-kitchen/kitchen-ec2/pull/41) ([sethvargo](https://github.com/sethvargo)) - IAM Profile Support for Created instance [\#35](https://github.com/test-kitchen/kitchen-ec2/pull/35) ([nicgrayson](https://github.com/nicgrayson)) ## [v0.8.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.8.0) (2014-02-12) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.7.0...v0.8.0) **Fixed bugs:** - AWS ENV vars not honored [\#17](https://github.com/test-kitchen/kitchen-ec2/issues/17) - Periodic failures in kitchen-ec2 [\#10](https://github.com/test-kitchen/kitchen-ec2/issues/10) **Closed issues:** - encrypted\_data\_bag\_secret not found [\#24](https://github.com/test-kitchen/kitchen-ec2/issues/24) - busser bats tests don't run [\#16](https://github.com/test-kitchen/kitchen-ec2/issues/16) - Support for server.dns\_name [\#14](https://github.com/test-kitchen/kitchen-ec2/issues/14) **Merged pull requests:** - Support AWS session tokens for use with IAM roles. [\#34](https://github.com/test-kitchen/kitchen-ec2/pull/34) ([coderanger](https://github.com/coderanger)) - endpoint should have a trailing slash [\#31](https://github.com/test-kitchen/kitchen-ec2/pull/31) ([spheromak](https://github.com/spheromak)) - Compat with test-kitchen master. [\#29](https://github.com/test-kitchen/kitchen-ec2/pull/29) ([coderanger](https://github.com/coderanger)) - Support selection of private ip [\#21](https://github.com/test-kitchen/kitchen-ec2/pull/21) ([Atalanta](https://github.com/Atalanta)) ## [v0.7.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.7.0) (2013-08-29) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.6.0...v0.7.0) **Closed issues:** - Error running kitchen-ec2 0.6.0 [\#12](https://github.com/test-kitchen/kitchen-ec2/issues/12) - License missing from gemspec [\#11](https://github.com/test-kitchen/kitchen-ec2/issues/11) **Merged pull requests:** - wait\_for\_ssh takes 2 arguments [\#13](https://github.com/test-kitchen/kitchen-ec2/pull/13) ([dysinger](https://github.com/dysinger)) ## [v0.6.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.6.0) (2013-07-23) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.5.1...v0.6.0) **Closed issues:** - net-scp version is 1.0.4 [\#1](https://github.com/test-kitchen/kitchen-ec2/issues/1) **Merged pull requests:** - Match access and secret key env vars in example kitchen config with CLI tools' env vars. [\#9](https://github.com/test-kitchen/kitchen-ec2/pull/9) ([juliandunn](https://github.com/juliandunn)) - Use private ip if the public ip is nil [\#8](https://github.com/test-kitchen/kitchen-ec2/pull/8) ([dissonanz](https://github.com/dissonanz)) ## [v0.5.1](https://github.com/test-kitchen/kitchen-ec2/tree/v0.5.1) (2013-05-23) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.5.0...v0.5.1) **Merged pull requests:** - Adding subnet\_id option for use with VPCs [\#7](https://github.com/test-kitchen/kitchen-ec2/pull/7) ([dissonanz](https://github.com/dissonanz)) ## [v0.5.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.5.0) (2013-05-23) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.4.0...v0.5.0) **Closed issues:** - We should be able to specify tags for ec2 instances [\#4](https://github.com/test-kitchen/kitchen-ec2/issues/4) - SSH private key config value needed [\#3](https://github.com/test-kitchen/kitchen-ec2/issues/3) **Merged pull requests:** - Add the ability to give ec2 instances tags. [\#5](https://github.com/test-kitchen/kitchen-ec2/pull/5) ([halcyonCorsair](https://github.com/halcyonCorsair)) - additional ec2 debugging [\#2](https://github.com/test-kitchen/kitchen-ec2/pull/2) ([mattray](https://github.com/mattray)) ## [v0.4.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.4.0) (2013-03-02) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.3.0...v0.4.0) ## [v0.3.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.3.0) (2013-01-09) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.2.0...v0.3.0) ## [v0.2.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.2.0) (2013-01-03) [Full Changelog](https://github.com/test-kitchen/kitchen-ec2/compare/v0.1.0...v0.2.0) ## [v0.1.0](https://github.com/test-kitchen/kitchen-ec2/tree/v0.1.0) (2012-12-27) \* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Code of Conduct Please refer to the Chef Community Code of Conduct at ================================================ FILE: Gemfile ================================================ source "https://rubygems.org" # Specify your gem's dependencies in kitchen-ec2.gemspec gemspec group :test do gem "rake", ">= 11.0" gem "rspec", "~> 3.2" end group :debug do gem "pry" end group :cookstyle do gem "cookstyle", "~> 8.1" end ================================================ FILE: LICENSE ================================================ Author:: Fletcher Nichol () Copyright (C) 2012, Fletcher Nichol Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # kitchen-ec2 [![Gem Version](https://badge.fury.io/rb/kitchen-ec2.svg)](https://badge.fury.io/rb/kitchen-ec2) ![CI](https://github.com/test-kitchen/kitchen-ec2/workflows/Test/badge.svg?branch=main) A [Test Kitchen][kitchenci] Driver for Amazon EC2. This driver uses the [aws sdk gem][aws_sdk_gem] to provision and destroy EC2 instances. Use Amazon's cloud for your infrastructure testing! ## Quick Start 1. Install [Chef Workstation](https://www.chef.io/downloads). If testing things other than Chef Infra cookbooks, please consult your driver's documentation for information on what to install. 2. Install the [AWS command line tools](https://docs.aws.amazon.com/cli/latest/userguide/installing.html). 3. Run `aws configure`. This will set up your AWS credentials for both the AWS CLI tools and kitchen-ec2. 4. Add or edit the `driver` section of your `kitchen.yml`: ```yaml driver: name: ec2 ``` 5. Run `kitchen test`. ## Requirements There are **no** external system requirements for this driver. However you will need access to an [AWS][aws_site] account. [IAM][iam_site] users should have, at a minimum, permission to manage the lifecycle of an EC2 instance along with modifying components specified in kitchen driver configs. Consider using a permissive managed IAM policy like ``arn:aws:iam::aws:policy/AmazonEC2FullAccess`` or tailor one specific to your security requirements. ## Configuration By automatically applying reasonable defaults wherever possible, kitchen-ec2 does a lot of work to make your life easier. See the [kitchen.ci kitchen-ec2 docs](https://kitchen.ci/docs/drivers/aws/) for a complete list of configuration options. ### Transport Options kitchen-ec2 supports multiple transport methods for connecting to EC2 instances: - **SSH/WinRM** (default): Traditional network-based access - **Instance Connect**: AWS EC2 Instance Connect for temporary SSH access - **SSM Session Manager**: AWS Systems Manager Session Manager for secure, audited access without SSH/RDP ports For SSM Session Manager configuration and benefits, see [SSM Session Manager Documentation](docs/ssm-session-manager.md). ## Development * Source hosted at [GitHub][repo] * Report issues/questions/feature requests on [GitHub Issues][issues] Pull requests are very welcome! Make sure your patches are well tested. Ideally create a topic branch for every separate change you make. For example: 1. Fork the repo 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Added some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request ## License Apache 2.0 (see [LICENSE][license]) [issues]: https://github.com/test-kitchen/kitchen-ec2/issues [license]: https://github.com/test-kitchen/kitchen-ec2/blob/master/LICENSE [repo]: https://github.com/test-kitchen/kitchen-ec2 [aws_site]: https://aws.amazon.com/ [iam_site]: https://aws.amazon.com/iam [aws_sdk_gem]: https://docs.aws.amazon.com/sdk-for-ruby/v3/api/ [kitchenci]: https://kitchen.ci/ ================================================ FILE: Rakefile ================================================ require "bundler/gem_tasks" require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:test) begin require "cookstyle/chefstyle" require "rubocop/rake_task" RuboCop::RakeTask.new(:style) do |task| task.options += ["--display-cop-names", "--no-color"] end rescue LoadError puts "cookstyle/chefstyle is not available. (sudo) gem install cookstyle to do style checking." end task default: %i{test style} ================================================ FILE: docs/ssm-session-manager.md ================================================ # AWS SSM Session Manager Support kitchen-ec2 now supports AWS Systems Manager (SSM) Session Manager as an alternative transport method to SSH/WinRM. This feature enables Test Kitchen to connect to EC2 instances without requiring direct network connectivity or SSH key management. ## Benefits - **No SSH/WinRM network access required**: Connect to instances in private subnets without VPN or bastion hosts - **Enhanced security**: No need to open SSH/RDP ports in security groups - **Centralized audit logging**: All session activity is logged to CloudTrail - **No SSH key management**: Eliminate the complexity of managing SSH key pairs for testing - **Zero-trust compliance**: Access instances through AWS IAM authentication instead of network-based access ## Requirements ### Client Requirements 1. **AWS CLI**: Install the AWS CLI version 2.x or later 2. **Session Manager Plugin**: Install the Session Manager plugin for AWS CLI ### Instance Requirements 1. **SSM Agent**: Must be installed and running on the EC2 instance 2. **IAM Instance Profile**: Instance must have the `AmazonSSMManagedInstanceCore` managed policy or equivalent 3. **Network Access**: Outbound HTTPS (port 443) access to AWS SSM endpoints ## Configuration ### Basic Configuration ```yaml driver: name: ec2 use_ssm_session_manager: true iam_profile_name: my-ssm-enabled-profile ``` ### Complete Example ```yaml driver: name: ec2 use_ssm_session_manager: true instance_type: t3.micro subnet_id: subnet-12345678 iam_profile_name: kitchen-ec2-ssm-profile security_group_ids: - sg-87654321 platforms: - name: amazon2 - name: ubuntu-20.04 suites: - name: default run_list: - recipe[my_cookbook::default] ``` ## Configuration Options | Option | Default | Description | |--------|---------|-------------| | `use_ssm_session_manager` | `false` | Enable SSM Session Manager transport | | `ssm_session_manager_document_name` | `nil` | Optional custom SSM document name | | `iam_profile_name` | `nil` | IAM instance profile (required for SSM) | ## Additional Resources - [AWS Systems Manager Session Manager Documentation](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html) - [Session Manager Plugin Installation](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) ================================================ FILE: kitchen-ec2.gemspec ================================================ lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "kitchen/driver/ec2_version" Gem::Specification.new do |gem| gem.name = "kitchen-ec2" gem.version = Kitchen::Driver::EC2_VERSION gem.license = "Apache-2.0" gem.authors = ["Test Kitchen Team"] gem.email = ["help@sous-chefs.org"] gem.description = "A Test Kitchen Driver for Amazon EC2" gem.summary = gem.description gem.homepage = "https://github.com/test-kitchen/kitchen-ec2" gem.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR).grep(/LICENSE|^lib/) gem.require_paths = ["lib"] gem.required_ruby_version = ">= 3.1" gem.add_dependency "aws-sdk-ec2", "~> 1.0" gem.add_dependency "aws-sdk-ec2instanceconnect", "~> 1.0" gem.add_dependency "aws-sdk-ssm", "~> 1.0" gem.add_dependency "retryable", ">= 2.0", "< 4.0" # 4.0 will need to be validated gem.add_dependency "sshkey", "~> 2.0" gem.add_dependency "test-kitchen", ">= 3.9.0", "< 5" end ================================================ FILE: lib/kitchen/driver/aws/client.rb ================================================ # # Author:: Tyler Ball () # # Copyright:: 2016-2018, Chef Software, Inc. # Copyright:: 2015-2018, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "aws-sdk-ec2" require "aws-sdk-core/credentials" require "aws-sdk-core/shared_credentials" require "aws-sdk-core/instance_profile_credentials" module Kitchen module Driver class Aws # A class for creating and managing the EC2 client connection # # @author Tyler Ball class Client def initialize( region, profile_name = "default", http_proxy = nil, retry_limit = nil, ssl_verify_peer = true ) ::Aws.config.update( region:, profile: profile_name, http_proxy:, ssl_verify_peer: ) ::Aws.config.update(retry_limit:) unless retry_limit.nil? end # create a new AWS EC2 instance # @param options [Hash] has of instance options # @see https://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Resource.html#create_instances-instance_method # @return [Aws::EC2::Instance] def create_instance(options) resource.create_instances(options).first end # get an instance object given an id # @param id [String] aws instance id # @return [Aws::EC2::Instance] def get_instance(id) resource.instance(id) end # get an instance object given a spot request ID # @param request_id [String] aws spot instance id # @return [Aws::EC2::Instance] def get_instance_from_spot_request(request_id) resource.instances( filters: [{ name: "spot-instance-request-id", values: [request_id], }] ).to_a[0] end # check if instance exists, given an id # @param id [String] aws instance id # @return boolean def instance_exists?(id) resource.instance(id).exists? end def client @client ||= ::Aws::EC2::Client.new end def resource @resource ||= ::Aws::EC2::Resource.new end end end end end ================================================ FILE: lib/kitchen/driver/aws/dedicated_hosts.rb ================================================ module Kitchen module Driver module Mixins module DedicatedHosts # check if a suitable dedicated host is available # @return Boolean def host_available? !hosts_with_capacity.empty? end # get dedicated host with capacity for instance type # @return Aws::EC2::Types::Host def hosts_with_capacity hosts_managed.select do |host| # T-instance hosts do not report available capacity and can be overprovisioned if host.available_capacity.nil? true else instance_capacity = host.available_capacity.available_instance_capacity capacity_for_type = instance_capacity.detect { |cap| cap.instance_type == config[:instance_type] } capacity_for_type.available_capacity > 0 end end end # check if host has no instances running # @param host_id [Aws::EC2::Types::Host] dedicated host # @return Boolean def host_unused?(host) host.instances.empty? end # get host data for host id # @param host_id [Aws::EC2::Types::Host] dedicated host # @return Array(Aws::EC2::Types::Host) def host_for_id(host_id) ec2.client.describe_hosts(host_ids: [host_id])&.first end # get dedicated hosts managed by Test Kitchen # @return Array(Aws::EC2::Types::Host) def hosts_managed response = ec2.client.describe_hosts( filter: [ { name: "tag:ManagedBy", values: ["Test Kitchen"] }, ] ) response.hosts.select { |host| host.state == "available" } end # allocate new dedicated host for requested instance type # @return String host id def allocate_host unless allow_allocate_host? warn "ERROR: Attempted to allocate dedicated host but need environment variable TK_ALLOCATE_DEDICATED_HOST to be set" exit! end unless config[:availability_zone] warn "Attempted to allocate dedicated host but option 'availability_zone' is not set" exit! end info("Allocating dedicated host for #{config[:instance_type]} instances. This will incur additional cost") request = { availability_zone: config[:availability_zone], quantity: 1, auto_placement: "on", tag_specifications: [ { resource_type: "dedicated-host", tags: [ { key: "ManagedBy", value: "Test Kitchen" }, ], }, ], } # ".metal" is a 1:1 association, everything else has multi-instance capability if instance_size_from_type(config[:instance_type]) == "metal" request[:instance_type] = config[:instance_type] else request[:instance_family] = instance_family_from_type(config[:instance_type]) end response = ec2.client.allocate_hosts(request) response.host_ids.first end # deallocate a dedicated host # @param host_id [String] dedicated host id # @return Aws::EC2::Types::ReleaseHostsResult def deallocate_host(host_id) info("Deallocating dedicated host #{host_id}") response = ec2.client.release_hosts({ host_ids: [host_id] }) return if response.unsuccessful.empty? warn "ERROR: Could not release dedicated host #{host_id}. Host may remain allocated and incur cost" exit! end # return instance family from type # @param instance_type [String] type in format family.size # @return String instance family def instance_family_from_type(instance_type) instance_type.split(".").first end # return instance size from type # @param instance_type [String] type in format family.size # @return String instance size def instance_size_from_type(instance_type) instance_type.split(".").last end # check config, if host allocation is enabled # @return Boolean def allow_allocate_host? config[:allocate_dedicated_host] end # check config, if host deallocation is enabled # @return Boolean def allow_deallocate_host? config[:deallocate_dedicated_host] end end end end end ================================================ FILE: lib/kitchen/driver/aws/instance_connect.rb ================================================ # # Author:: Alex Kokkinos # # Copyright:: 2025, Alex Kokkinos # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "aws-sdk-ec2instanceconnect" module Kitchen module Driver class Aws class InstanceConnect def initialize(config, logger) @config = config @logger = logger @client = ::Aws::EC2InstanceConnect::Client.new(region: config[:region]) end def send_ssh_public_key(instance_id, username, public_key) @logger.info("Sending SSH public key to instance #{instance_id} for user #{username}") @client.send_ssh_public_key({ instance_id: instance_id, instance_os_user: username, ssh_public_key: public_key, availability_zone: @config[:availability_zone], }) @logger.debug("SSH public key successfully sent to instance") end end end end end ================================================ FILE: lib/kitchen/driver/aws/instance_generator.rb ================================================ # # Author:: Tyler Ball () # # Copyright:: 2016-2018, Chef Software, Inc. # Copyright:: 2015-2018, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "base64" unless defined?(Base64) require "aws-sdk-ec2" module Kitchen module Driver class Aws # A class for encapsulating the instance payload logic # # @author Tyler Ball class InstanceGenerator attr_reader :config, :ec2, :logger def initialize(config, ec2, logger) @config = config @ec2 = ec2 @logger = logger end # Transform the provided kitchen config into the hash we'll use to create the aws instance # can be passed in null, others need to be omitted if they are null # Some fields can be passed in null, others need to be omitted if they are null # @return [Hash] def ec2_instance_data # Support for looking up security group id and subnet id using tags. vpc_id = nil client = ::Aws::EC2::Client.new(region: config[:region]) if config[:subnet_id].nil? && config[:subnet_filter] filters = [config[:subnet_filter]].flatten r = { filters: [] } filters.each do |subnet_filter| r[:filters] << { name: "tag:#{subnet_filter[:tag]}", values: [subnet_filter[:value]], } end subnets = client.describe_subnets(r).subnets raise "Subnets with tags '#{filters}' not found during security group creation" if subnets.empty? # => Select the least-populated subnet if we have multiple matches subnet = subnets.max_by { |s| s[:available_ip_address_count] } vpc_id = subnet.vpc_id config[:subnet_id] = subnet.subnet_id end if config[:security_group_ids].nil? && config[:security_group_filter] # => Grab the VPC in the case a Subnet ID rather than Filter was set vpc_id ||= client.describe_subnets(subnet_ids: [config[:subnet_id]]).subnets[0].vpc_id security_groups = [] filters = [config[:security_group_filter]].flatten filters.each do |sg_filter| r = {} if sg_filter[:name] r[:filters] = [ { name: "group-name", values: [sg_filter[:name]], }, { name: "vpc-id", values: [vpc_id], }, ] end if sg_filter[:tag] r[:filters] = [ { name: "tag:#{sg_filter[:tag]}", values: [sg_filter[:value]], }, { name: "vpc-id", values: [vpc_id], }, ] end security_group = client.describe_security_groups(r).security_groups if security_group.any? security_group.each { |sg| security_groups.push(sg.group_id) } else raise "A Security Group matching the following filter could not be found:\n#{sg_filter}" end end config[:security_group_ids] = security_groups end i = { instance_type: config[:instance_type], ebs_optimized: config[:ebs_optimized], image_id: config[:image_id], key_name: config[:aws_ssh_key_id], subnet_id: config[:subnet_id], private_ip_address: config[:private_ip_address], min_count: 1, max_count: 1, } if config[:tags] && !config[:tags].empty? tags = config[:tags].map do |k, v| # we convert the value to a string because # nils should be passed as an empty String # and Integers need to be represented as Strings { key: k, value: v.to_s } end instance_tag_spec = { resource_type: "instance", tags: } volume_tag_spec = { resource_type: "volume", tags: } i[:tag_specifications] = [instance_tag_spec, volume_tag_spec] end availability_zone = config[:availability_zone] if availability_zone if /^[a-z]$/i.match?(availability_zone) availability_zone = "#{config[:region]}#{availability_zone}" end i[:placement] = { availability_zone: availability_zone.downcase } end tenancy = config[:tenancy] if tenancy if i.key?(:placement) i[:placement][:tenancy] = tenancy else i[:placement] = { tenancy: } end end unless config[:block_device_mappings].nil? || config[:block_device_mappings].empty? i[:block_device_mappings] = config[:block_device_mappings] end i[:security_group_ids] = Array(config[:security_group_ids]) if config[:security_group_ids] i[:metadata_options] = config[:metadata_options] if config[:metadata_options] i[:user_data] = prepared_user_data if prepared_user_data if config[:iam_profile_name] i[:iam_instance_profile] = { name: config[:iam_profile_name] } end unless config.fetch(:associate_public_ip, nil).nil? i[:network_interfaces] = [{ device_index: 0, associate_public_ip_address: config[:associate_public_ip], delete_on_termination: true, }] # If specifying `:network_interfaces` in the request, you must specify # network specific configs in the network_interfaces block and not at # the top level if config[:subnet_id] i[:network_interfaces][0][:subnet_id] = i.delete(:subnet_id) end if config[:private_ip_address] i[:network_interfaces][0][:private_ip_address] = i.delete(:private_ip_address) end if config[:security_group_ids] i[:network_interfaces][0][:groups] = i.delete(:security_group_ids) end if config[:associate_ipv6] i[:network_interfaces][0][:ipv_6_address_count] = 1 end end availability_zone = config[:availability_zone] if availability_zone if /^[a-z]$/i.match?(availability_zone) availability_zone = "#{config[:region]}#{availability_zone}" end i[:placement] = { availability_zone: availability_zone.downcase } end tenancy = config[:tenancy] if tenancy if i.key?(:placement) i[:placement][:tenancy] = tenancy else i[:placement] = { tenancy: } end end placement = config[:placement] if placement unless i.key?(:placement) i[:placement] = {} end if placement[:affinity] i[:placement][:affinity] = placement[:affinity] end if placement[:availability_zone] i[:placement][:availability_zone] = placement[:availability_zone] end if placement[:group_id] && !placement[:group_name] i[:placement][:group_id] = placement[:group_id] end if placement[:group_name] && !placement[:group_id] i[:placement][:group_name] = placement[:group_name] end if placement[:host_id] i[:placement][:host_id] = placement[:host_id] end if placement[:host_resource_group_arn] i[:placement][:host_resource_group_arn] = placement[:host_resource_group_arn] end if placement[:partition_number] i[:placement][:partition_number] = placement[:partition_number] end if placement[:tenancy] i[:placement][:tenancy] = placement[:tenancy] end end license_specifications = config[:licenses] if license_specifications i[:licenses] = [] license_specifications.each do |license_configuration_arn| i[:licenses].append({ license_configuration_arn: license_configuration_arn[:license_configuration_arn] }) end end unless config[:instance_initiated_shutdown_behavior].nil? || config[:instance_initiated_shutdown_behavior].empty? i[:instance_initiated_shutdown_behavior] = config[:instance_initiated_shutdown_behavior] end i end def prepared_user_data # If user_data is a file reference, lets read it as such return nil if config[:user_data].nil? return @user_data if @user_data raw_user_data = config.fetch(:user_data) if !raw_user_data.include?("\0") && File.file?(raw_user_data) raw_user_data = File.read(raw_user_data) end @user_data = Base64.encode64(raw_user_data) end end end end end ================================================ FILE: lib/kitchen/driver/aws/ssm_session_manager.rb ================================================ # # Author:: GitHub Copilot # # Copyright:: 2025, GitHub # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "aws-sdk-ssm" require "open3" module Kitchen module Driver class Aws # Manages AWS Systems Manager Session Manager connections for Test Kitchen class SsmSessionManager def initialize(config, logger) @config = config @logger = logger @ssm_client = ::Aws::SSM::Client.new( region: config[:region], profile: config[:shared_credentials_profile] ) end # Check if SSM agent is running on the instance def ssm_agent_available?(instance_id) @logger.debug("Checking if SSM agent is available on instance #{instance_id}") begin resp = @ssm_client.describe_instance_information( filters: [ { key: "InstanceIds", values: [instance_id], }, ] ) available = !resp.instance_information_list.empty? && resp.instance_information_list.first.ping_status == "Online" if available @logger.info("SSM agent is available on instance #{instance_id}") else @logger.warn("SSM agent is not available on instance #{instance_id}") end available rescue ::Aws::SSM::Errors::ServiceError => e @logger.warn("Error checking SSM agent status: #{e.message}") false end end # Verify that the AWS CLI session manager plugin is installed def session_manager_plugin_installed? _output, status = Open3.capture2e("session-manager-plugin", "--version") installed = status.success? if installed @logger.debug("Session Manager plugin is installed") else @logger.warn("Session Manager plugin is not installed. Install it from: " \ "https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html") end installed rescue StandardError => e @logger.warn("Error checking for session-manager-plugin: #{e.message}") false end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/alma.rb ================================================ # # Copyright:: 2023, Jared Kauppila # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://wiki.almalinux.org/cloud/AWS.html class Alma < StandardPlatform StandardPlatform.platforms["alma"] = self StandardPlatform.platforms["almalinux"] = self # default username for this platform's ami # @return [String] def username "ec2-user" end def image_search search = { "owner-id" => "764336703387", "name" => version ? "AlmaLinux OS #{version}*" : "AlmaLinux OS *", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /AlmaLinux OS/i.match?(image.name) image.name =~ /\b(\d+(\.\d+)?)\b/i new(driver, "alma", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/amazon.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://aws.amazon.com/amazon-linux-ami/ class Amazon < StandardPlatform StandardPlatform.platforms["amazon"] = self # default username for this platform's ami # @return [String] def username "ec2-user" end def image_search search = { "owner-id" => "137112412989", "name" => version ? "amzn-ami-*-#{version}*" : "amzn-ami-*", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /amzn-ami/i.match?(image.name) image.name =~ /\b(\d+(\.\d+[\.\d])?)/i new(driver, "amazon", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/amazon2.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://aws.amazon.com/de/amazon-linux-2/release-notes/ class Amazon2 < StandardPlatform StandardPlatform.platforms["amazon2"] = self # default username for this platform's ami # @return [String] def username "ec2-user" end def image_search search = { "owner-id" => "137112412989", "name" => version ? "amzn2-ami-hvm-2.0.#{version}*" : "amzn2-ami-hvm-2.0.*", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /amzn2-ami/i.match?(image.name) image.name =~ /\b(\d+(\.\d+[\.\d])?)/i new(driver, "amazon2", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/amazon2023.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://docs.aws.amazon.com/linux/al2023/release-notes/relnotes.html class Amazon2023 < StandardPlatform StandardPlatform.platforms["amazon2023"] = self # default username for this platform's ami # @return [String] def username "ec2-user" end def image_search search = { "owner-id" => "137112412989", "name" => version ? "al2023-ami-2023.#{version}*" : "al2023-ami-2023.*", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /al2023-ami/i.match?(image.name) image.name =~ /\b(\d+(\.\d+[\.\d])?)/i new(driver, "amazon2023", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/centos.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://wiki.centos.org/Cloud/AWS class Centos < StandardPlatform StandardPlatform.platforms["centos"] = self CENTOS_OWNER_ID = "125523088429".freeze # default username for this platform's ami # @return [String] def username version && version.to_f < 9.0 ? "centos" : "ec2-user" end def image_search # Version 8+ are published directly, not to the AWS marketplace. Use OWNER ID. search = { "owner-id" => CENTOS_OWNER_ID, "name" => ["CentOS #{version}*", "CentOS-#{version}*-GA-*", "CentOS Linux #{version}*", "CentOS Stream #{version}*"], } search["architecture"] = architecture if architecture search end def sort_by_version(images) # 7.1 -> [ img1, img2, img3 ] # 6 -> [ img4, img5 ] # ... images.group_by { |image| self.class.from_image(driver, image).version } .sort_by { |k, _v| (k && k.include?(".") ? k.to_f : "#{k}.999".to_f) } .reverse.flat_map { |_k, v| v } end def self.from_image(driver, image) return unless /centos/i.match?(image.name) image.name =~ /\b(\d+(\.\d+)?)\b/i new(driver, "centos", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/debian.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://wiki.debian.org/Cloud/AmazonEC2Image class Debian < StandardPlatform StandardPlatform.platforms["debian"] = self DEBIAN_CODENAMES = { 13 => "trixie", 12 => "bookworm", 11 => "bullseye", 10 => "buster", 9 => "stretch", 8 => "jessie", 7 => "wheezy", 6 => "squeeze", }.freeze # default username for this platform's ami # @return [String] def username "admin" end def codename v = version if v && v.size > 1 warn("WARN: Debian version #{version} specified, but searching for #{version.to_i} instead.") v = v.to_i end v ? DEBIAN_CODENAMES[v.to_i] : DEBIAN_CODENAMES.values.first end def image_search search = {} # The Debian AWS owner ID changed for releases 10 and onwards # See https://wiki.debian.org/Amazon/EC2/HowTo/awscli if version.nil? search["owner-id"] = "136693071363" search["name"] = "debian-#{DEBIAN_CODENAMES.keys.first}-*" elsif version.to_i >= 10 search["owner-id"] = "136693071363" search["name"] = "debian-#{version.to_i}-*" else search["owner-id"] = "379101102735" search["name"] = "debian-#{codename}-*" end search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /debian/i.match?(image.name) image.name =~ /\b(\d+|#{DEBIAN_CODENAMES.values.join("|")})\b/i version = (Regexp.last_match || [])[1] if version&.to_i&.zero? version = DEBIAN_CODENAMES.find do |_v, codename| codename == version.downcase end.first end new(driver, "debian", version, image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/fedora.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/Cloud_Guide/ch02.html#id697643 class Fedora < StandardPlatform StandardPlatform.platforms["fedora"] = self # default username for this platform's ami # @return [String] def username "fedora" end def image_search search = { "owner-id" => "125523088429", "name" => version ? "Fedora-Cloud-Base-#{version}-*" : "Fedora-Cloud-Base-*", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /fedora/i.match?(image.name) image.name =~ /\b(\d+(\.\d+)?)\b/i new(driver, "fedora", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/freebsd.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # http://www.daemonology.net/freebsd-on-ec2/ class Freebsd < StandardPlatform StandardPlatform.platforms["freebsd"] = self # default username for this platform's ami # @return [String] def username "ec2-user" end def sudo_command; end def image_search search = { "owner-id" => "118940168514", "name" => ["FreeBSD #{version}*-RELEASE*", "FreeBSD/EC2 #{version}*-RELEASE*"], } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /freebsd/i.match?(image.name) image.name =~ /\b(\d+(\.\d+)?)\b/i new(driver, "freebsd", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/macos.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform class MacOS < StandardPlatform StandardPlatform.platforms["macos"] = self # default username for this platform's ami # @return [String] def username "ec2-user" end def image_search search = { "owner-id" => "100343932686", "name" => version ? "amzn-ec2-macos-#{version}*" : "amzn2-ec2-macos-*", } search["architecture"] = architecture if architecture search["architecture"] = "arm64_mac" if architecture == "arm64" search end def self.from_image(driver, image) return unless /amzn-ec2-macos/i.match?(image.name) image.name =~ /\b(\d+(\.\d+[\.\d])?)/i new(driver, "macos", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/rhel.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://aws.amazon.com/blogs/aws/now-available-red-hat-enterprise-linux-64-amis/ class El < StandardPlatform StandardPlatform.platforms["rhel"] = self StandardPlatform.platforms["el"] = self def initialize(driver, _name, version, architecture) # rhel = el super(driver, "rhel", version, architecture) end # default username for this platform's ami # @return [String] def username version && version.to_f < 6.4 ? "root" : "ec2-user" end def image_search search = { "owner-id" => "309956199498", "name" => "RHEL-#{version}*", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /rhel/i.match?(image.name) image.name =~ /\b(\d+(\.\d+)?)/i new(driver, "rhel", (Regexp.last_match || [])[1], image.architecture) end def sort_by_version(images) # First do a normal version sort super(images) # Now sort again, shunning Beta releases. prefer(images) { |image| !image.name.match(/_Beta-/i) } end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/rocky.rb ================================================ # # Copyright:: 2023, Jared Kauppila # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform class Rocky < StandardPlatform StandardPlatform.platforms["rocky"] = self StandardPlatform.platforms["rockylinux"] = self # default username for this platform's ami # @return [String] def username "rocky" end def image_search search = { "owner-id" => "792107900819", "name" => version ? "Rocky-#{version}-*" : "Rocky-*", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /Rocky-/i.match?(image.name) image.name =~ /\b(\d+(\.\d+[\.\d])?)/i new(driver, "rocky", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/ubuntu.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # https://help.ubuntu.com/community/EC2StartersGuide#Official_Ubuntu_Cloud_Guest_Amazon_Machine_Images_.28AMIs.29 class Ubuntu < StandardPlatform StandardPlatform.platforms["ubuntu"] = self # default username for this platform's ami # @return [String] def username "ubuntu" end def image_search search = { "owner-id" => "099720109477", "name" => "ubuntu/images/*/ubuntu-*-#{version}*", } search["architecture"] = architecture if architecture search end def self.from_image(driver, image) return unless /ubuntu/i.match?(image.name) image.name =~ /\b(\d+(\.\d+)?)\b/i new(driver, "ubuntu", (Regexp.last_match || [])[1], image.architecture) end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform/windows.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../standard_platform" module Kitchen module Driver class Aws class StandardPlatform # http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/finding-an-ami.html class Windows < StandardPlatform StandardPlatform.platforms["windows"] = self # default username for this platform's ami # @return [String] def username "administrator" end # Figure out the right set of names to search for: # # "windows" -> [nil, nil, nil] # Windows_Server-*-R*_RTM-, Windows_Server-*-R*_SP*-, # Windows_Server-*-RTM-, Windows_Server-*-SP*-, # Windows_Server-*- # "windows-2012" -> [2012, 0, nil] # Windows_Server-2012-RTM-, Windows_Server-2012-SP*- # "windows-2012r2" -> [2012, 2, nil] # Windows_Server-2012-R2_RTM-, Windows_Server-2012-R2_SP*- # "windows-2012sp1" -> [2012, 0, 1] # Windows_Server-2012-SP1- # "windows-2012rtm" -> [2012, 0, 0] # Windows_Server-2012-RTM- # "windows-2012r2sp1" -> [2012, 2, 1] # Windows_Server-2012-R2_SP1- # "windows-2012r2rtm" -> [2012, 2, 0] # Windows_Server-2012-R2_RTM- # "windows-2016" -> [2016, 0, nil] # Windows_Server-2016- # "windows-2019" -> [2019, 0, nil] # Windows_Server-2019- def image_search search = { "owner-alias" => "amazon", "name" => windows_name_filter, } search["architecture"] = architecture if architecture search end def sort_by_version(images) # 2008r2rtm -> [ img1, img2, img3 ] # 2012r2sp1 -> [ img4, img5 ] # ... images.group_by { |image| self.class.from_image(driver, image).windows_version_parts } .sort_by { |version, _platform_images| version } .reverse.flat_map { |_version, platform_images| platform_images } end def self.from_image(driver, image) return unless /Windows/i.match?(image.name) # 2008 R2 SP2 if image.name =~ /(\b\d+)\W*(r\d+)?/i major = (Regexp.last_match || [])[1] revision = (Regexp.last_match || [])[2] service_pack = (Regexp.last_match || [])[1] if image.name =~ /(sp\d+|rtm)/i revision = revision.downcase if revision service_pack ||= "rtm" service_pack = service_pack.downcase version = "#{major}#{revision}#{service_pack}" end new(driver, "windows", version, image.architecture) end protected # Turn windows version into [ major, revision, service_pack ] # # nil -> [ nil, nil, nil ] # 2012 -> [ 2012, 0, nil ] # 2012r2 -> [ 2012, 2, nil ] # 2012r2sp4 -> [ 2012, 2, 4 ] # 2012sp4 -> [ 2012, 0, 4 ] # 2012rtm -> [ 2012, 0, 0 ] # 2016 -> [ 2016, 0, nil ] # 2019 -> [ 2019, 0, nil ] # 1709 -> [ 1709, 0, nil ] # 1803 -> [ 1803, 0, nil ] def windows_version_parts version = self.version if version # windows-server-* -> windows-* if version.split("-", 2)[0] == "server" version = version.split("-", 2)[1] end if version =~ /^(\d+)(r\d+)?(sp\d+|rtm)?$/i major, revision, service_pack = Regexp.last_match[1..3] end end if major # Get major as an integer (2008 -> 2008, 7 -> 7) major = major.to_i # Get revision as an integer (no revision -> 0, R1 -> 1). revision = revision ? revision[1..-1].to_i : 0 # Turn service_pack into an integer. rtm = 0, spN = N. if service_pack service_pack = (service_pack.casecmp("rtm") == 0) ? 0 : service_pack[2..-1].to_i end end [major, revision, service_pack] end private def windows_name_filter major, revision, service_pack = windows_version_parts if [2025, 2022, 2019, 2016].include?(major) "Windows_Server-#{major}-English-Full-Base-*" elsif [1709, 1803].include?(major) "Windows_Server-#{major}-English-Core-ContainersLatest-*" else revision_strings = case revision when nil ["", "R*_"] when 0 [""] else ["R#{revision}_"] end revision_strings = case service_pack when nil revision_strings.flat_map { |r| ["#{r}RTM", "#{r}SP*"] } when 0 revision_strings.map { |r| "#{r}RTM" } else revision_strings.map { |r| "#{r}SP#{service_pack}" } end name_filter = revision_strings.map do |r| "Windows_Server-#{major || "*"}-#{r}-English-*-Base-*" end name_filter << "Windows_Server-*-English-Full-Base-*" if major.nil? name_filter end end end end end end end ================================================ FILE: lib/kitchen/driver/aws/standard_platform.rb ================================================ # # Copyright:: 2016-2018, Chef Software, Inc. # Copyright:: 2015-2018, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Kitchen module Driver class Aws # # Lets you grab StandardPlatform objects that help search for official # AMIs in your region and tell you useful tidbits like usernames. # # To use these, set your platform name to a supported platform name like: # # centos # rhel # fedora # freebsd # macos # ubuntu # windows # # The implementation will select the latest matching version and AMI. # # You can specify a version and optional architecture as well: # # windows-2012r2-i386 # centos-7 # # Useful reference for platform AMIs: # https://alestic.com/2014/01/ec2-ssh-username/ class StandardPlatform # # Create a new StandardPlatform object. # # @param driver [Kitchen::Driver::Ec2] The driver. # @param name [String] The name of the platform (rhel, centos, etc.) # @param version [String] The version of the platform (7.1, 2008sp1, etc.) # @param architecture [String] The architecture (i386, x86_64, arm64) # def initialize(driver, name, version, architecture) @driver = driver @name = name @version = version @architecture = architecture end # # The driver. # # @return [Kitchen::Driver::Ec2] # attr_reader :driver # # The name of the platform (e.g. rhel, centos, etc.) # # @return [String] # attr_reader :name # # The version of the platform (e.g. 7.1, 2008sp1, etc.) # # @return [String] # attr_reader :version # # The architecture of the platform, e.g. i386, x86_64 # # @return [String] # # @see SUPPORTED_ARCHITECTURES # attr_reader :architecture # # The list of supported architectures # SUPPORTED_ARCHITECTURES = %w{x86_64 i386 arm64}.freeze # # The list of supported ebs volume types # EBS_VOLUME_TYPES = %w{gp3 gp2}.freeze # # Find the best matching image for the given image search. # # @return [String] The image ID (e.g. ami-213984723) def find_image(image_search) driver.debug("Searching for images matching #{image_search} ...") # Convert to ec2 search format (pairs of name+values) filters = image_search.map do |key, value| { name: key.to_s, values: Array(value).map(&:to_s) } end # We prefer most recent first images = driver.ec2.resource.images(filters:) images = sort_images(images) show_returned_images(images) # Grab the best match images.first&.id end # # The list of StandardPlatform objects. StandardPlatforms register # themselves with this. # # @return Array[Kitchen::Driver::Aws::StandardPlatform] # def self.platforms @platforms ||= {} end def to_s "#{name}#{version ? " #{version}" : ""}#{architecture ? " #{architecture}" : ""}" end # # Instantiate a platform from a platform name. # # @param driver [Kitchen::Driver::Ec2] The driver. # @param platform_string [String] The platform string, e.g. "windows", # "ubuntu-7.1", "centos-7-i386" # # @return [Kitchen::Driver::Aws::StandardPlatform] # def self.from_platform_string(driver, platform_string) platform, version, architecture = parse_platform_string(platform_string) return unless platform && platforms[platform] platforms[platform].new(driver, platform, version, architecture) end # # Detect platform from an image. # # @param driver [Kitchen::Driver::Ec2] The driver. # @param image [Aws::Ec2::Image] The EC2 Image object. # # @return [Kitchen::Driver::Aws::StandardPlatform] # def self.from_image(driver, image) platforms.each_value do |platform| result = platform.from_image(driver, image) return result if result end nil end def self.parse_platform_string(platform_string) platform, version = platform_string.split("-", 2) # If the right side is a valid architecture, use it as such # i.e. debian-i386 or windows-server-2012r2-i386 if version && SUPPORTED_ARCHITECTURES.include?(version.split("-")[-1]) # server-2012r2-i386 -> server-2012r2, -, i386 version, _dash, architecture = version.rpartition("-") version = nil if version == "" end [platform, version, architecture] end protected # # Sort a list of images by their versions, from greatest to least. # # This MUST perform a stable sort. (Note that `sort` and `sort_by` are # not, by default, stable sorts in Ruby.) # # Used by the default find_image. The default version calls platform_from_image() # on each image, and interprets the versions as floats (7 < 7.1 < 8). # # @param images [Array[Aws::Ec2::Image]] The list of images to sort # # @return [Array[Aws::Ec2::Image]] A sorted list. # def sort_by_version(images) # 7.1 -> [ img1, img2, img3 ] # 6 -> [ img4, img5 ] # ... images.group_by do |image| platform = self.class.from_image(driver, image) platform ? platform.version : nil end.sort_by { |k, _v| k ? k.to_f : nil }.reverse.flat_map { |_k, v| v } end # Not supported yet: aix mac_os_x nexus solaris def prefer(images, &block) # Put the matching ones *before* the non-matching ones. matching, non_matching = images.partition(&block) matching + non_matching end private def sort_images(images) # P6: We prefer more recent images over older ones images = images.sort_by(&:creation_date).reverse # P5: We prefer x86_64 over i386 (if available) images = prefer(images) { |image| image.architecture == "x86_64" } # P4: We prefer (SSD) (if available) images = prefer(images) do |image| image.block_device_mappings.any? do |b| b.device_name == image.root_device_name && b.ebs && EBS_VOLUME_TYPES.any?(b.ebs.volume_type) end end # P3: We prefer ebs over instance_store (if available) images = prefer(images) { |image| image.root_device_type == "ebs" } # P2: We prefer hvm (the modern standard) images = prefer(images) { |image| image.virtualization_type == "hvm" } # P1: We prefer the latest version over anything else sort_by_version(images) end def show_returned_images(images) if images.empty? driver.error("Search returned 0 images.") else driver.debug("Search returned #{images.size} images:") images.each do |image| platform = self.class.from_image(driver, image) if platform driver.debug("- #{image.name}: Detected #{platform}. #{driver.image_info(image)}") else driver.debug("- #{image.name}: No platform detected. #{driver.image_info(image)}") end end end end end end end end ================================================ FILE: lib/kitchen/driver/ec2.rb ================================================ # # Author:: Fletcher Nichol () # # Copyright:: 2016-2018, Chef Software, Inc. # Copyright:: 2015-2018, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "sshkey" unless defined?(SSHKey) require "benchmark" unless defined?(Benchmark) require "json" unless defined?(JSON) require "kitchen" require_relative "ec2_version" require_relative "aws/client" require_relative "aws/dedicated_hosts" require_relative "aws/instance_generator" require_relative "aws/standard_platform" require_relative "aws/standard_platform/alma" require_relative "aws/standard_platform/amazon" require_relative "aws/standard_platform/amazon2" require_relative "aws/standard_platform/amazon2023" require_relative "aws/standard_platform/centos" require_relative "aws/standard_platform/debian" require_relative "aws/standard_platform/rhel" require_relative "aws/standard_platform/rocky" require_relative "aws/standard_platform/fedora" require_relative "aws/standard_platform/freebsd" require_relative "aws/standard_platform/macos" require_relative "aws/standard_platform/ubuntu" require_relative "aws/standard_platform/windows" require_relative "aws/instance_connect" require_relative "aws/ssm_session_manager" require "aws-sdk-ec2" require "aws-sdk-core/waiters/errors" require "retryable" unless defined?(Retryable) require "time" unless defined?(Time) require "etc" unless defined?(Etc) require "socket" unless defined?(Socket) require "shellwords" unless defined?(Shellwords) module Kitchen module Driver # Amazon EC2 driver for Test Kitchen. # # @author Fletcher Nichol class Ec2 < Kitchen::Driver::Base kitchen_driver_api_version 2 plugin_version Kitchen::Driver::EC2_VERSION default_config :region, ENV["AWS_REGION"] || "us-east-1" default_config :shared_credentials_profile, ENV.fetch("AWS_PROFILE", nil) default_config :availability_zone, nil default_config :instance_type, &:default_instance_type default_config :ebs_optimized, false default_config :delete_on_termination, true default_config :security_group_ids, nil default_config :security_group_filter, nil default_config :security_group_cidr_ip, "0.0.0.0/0" default_config :tags, "created-by" => "test-kitchen" default_config :user_data do |driver| if driver.windows_os? driver.default_windows_user_data end end default_config :private_ip_address, nil default_config :iam_profile_name, nil default_config :spot_price, nil default_config :block_duration_minutes, nil default_config :retryable_tries, 60 default_config :spot_wait, 60 default_config :retryable_sleep, 5 default_config :aws_access_key_id, nil default_config :aws_secret_access_key, nil default_config :aws_session_token, nil default_config :aws_ssh_key_id, ENV.fetch("AWS_SSH_KEY_ID", nil) default_config :aws_ssh_key_type, "rsa" default_config :image_id, &:default_ami default_config :image_search, nil default_config :username, nil default_config :associate_public_ip, nil default_config :associate_ipv6, nil default_config :interface, nil default_config :http_proxy, ENV["HTTPS_PROXY"] || ENV.fetch("HTTP_PROXY", nil) default_config :retry_limit, 3 default_config :tenancy, "default" default_config :instance_initiated_shutdown_behavior, nil default_config :ssl_verify_peer, true default_config :skip_cost_warning, false default_config :allocate_dedicated_host, false default_config :deallocate_dedicated_host, false default_config :use_instance_connect, false default_config :instance_connect_endpoint_id, nil default_config :instance_connect_max_tunnel_duration, 3600 default_config :use_ssm_session_manager, false default_config :ssm_session_manager_document_name, nil include Kitchen::Driver::Mixins::DedicatedHosts def initialize(*args, &block) super end def self.validation_warn(driver, old_key, new_key) driver.warn "WARN: The driver[#{driver.class.name}] config key `#{old_key}` " \ "is deprecated, please use `#{new_key}`" end def self.validation_error(driver, old_key, new_key) warn "ERROR: The driver[#{driver.class.name}] config key `#{old_key}` " \ "has been removed, please use `#{new_key}`" exit! end # TODO: remove these in 1.1 deprecated_configs = %i{ebs_volume_size ebs_delete_on_termination ebs_device_name} deprecated_configs.each do |d| validations[d] = lambda do |attr, val, driver| unless val.nil? validation_error(driver, attr, "block_device_mappings") end end end validations[:ssh_key] = lambda do |attr, val, driver| unless val.nil? validation_error(driver, attr, "transport.ssh_key") end end validations[:ssh_timeout] = lambda do |attr, val, driver| unless val.nil? validation_error(driver, attr, "transport.connection_timeout") end end validations[:ssh_retries] = lambda do |attr, val, driver| unless val.nil? validation_error(driver, attr, "transport.connection_retries") end end validations[:username] = lambda do |attr, val, driver| unless val.nil? validation_error(driver, attr, "transport.username") end end validations[:flavor_id] = lambda do |attr, val, driver| unless val.nil? validation_error(driver, attr, "instance_type") end end # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html validations[:tenancy] = lambda do |attr, val, _driver| unless %w{default host dedicated}.include?(val) warn "'#{val}' is an invalid value for option '#{attr}'. " \ "Valid values are 'default', 'host', or 'dedicated'." exit! end end # The access key/secret are now using the priority list AWS uses # Providing these inside the .kitchen.yml is no longer recommended validations[:aws_access_key_id] = lambda do |attr, val, _driver| unless val.nil? warn "#{attr} is no longer a valid config option, please use " \ "ENV['AWS_ACCESS_KEY_ID'] or ~/.aws/credentials. See " \ "the README for more details" exit! end end validations[:aws_secret_access_key] = lambda do |attr, val, _driver| unless val.nil? warn "#{attr} is no longer a valid config option, please use " \ "ENV['AWS_SECRET_ACCESS_KEY'] or ~/.aws/credentials. See " \ "the README for more details" exit! end end validations[:aws_session_token] = lambda do |attr, val, _driver| unless val.nil? warn "#{attr} is no longer a valid config option, please use " \ "ENV['AWS_SESSION_TOKEN'] or ~/.aws/credentials. See " \ "the README for more details" exit! end end validations[:instance_initiated_shutdown_behavior] = lambda do |attr, val, _driver| unless [nil, "stop", "terminate"].include?(val) warn "'#{val}' is an invalid value for option '#{attr}'. " \ "Valid values are 'stop' or 'terminate'" exit! end end # Ensure use_instance_connect and use_ssm_session_manager are not both enabled validations[:use_ssm_session_manager] = lambda do |_attr, val, driver| if val && driver[:use_instance_connect] warn "Cannot use both 'use_instance_connect' and 'use_ssm_session_manager' at the same time. " \ "Please enable only one transport method." exit! end end # empty keys cause failures when tagging and they make no sense validations[:tags] = lambda do |_attr, val, _driver| # if someone puts the tags each on their own line it's an array not a hash # @todo we should probably just do the right thing and support this format if val.instance_of?(Array) warn "AWS instance tags must be specified as a single hash, not a tag " \ "on each line. Example: {:foo => 'bar', :bar => 'foo'}" exit! end end def create(state) return if state[:server_id] update_username(state) info(Kitchen::Util.outdent!(<<-END)) unless config[:skip_cost_warning] If you are not using an account that qualifies under the AWS free-tier, you may be charged to run these suites. The charge should be minimal, but neither Test Kitchen nor its maintainers are responsible for your incurred costs. END # If no security group IDs are specified, create one automatically. unless config[:security_group_ids] || config[:security_group_filter] create_security_group(state) config[:security_group_ids] = [state[:auto_security_group_id]] end # If no SSH key pair name is specified, create one automatically. # If `_disabled`, nullify the key ID to avoid associating the instance with # an AWS-managed key pair. case config[:aws_ssh_key_id] when nil create_key(state) # Don't set aws_ssh_key_id if using Instance Connect config[:aws_ssh_key_id] = state[:auto_key_id] unless config[:use_instance_connect] when "_disable" info("Disabling AWS-managed SSH key pairs for this EC2 instance.") info("The key pairs for the kitchen transport config and the AMI must match.") config[:aws_ssh_key_id] = nil end # Allocate new dedicated hosts if needed and allowed if config[:tenancy] == "host" unless host_available? || allow_allocate_host? warn "ERROR: tenancy `host` requested but no suitable host and allocation not allowed (set `allocate_dedicated_host` setting)" exit! end allocate_host unless host_available? info("Auto placement on one dedicated host out of: #{hosts_with_capacity.map(&:host_id).join(", ")}") end server = if config[:spot_price] # Spot instance when a price is set with_request_limit_backoff(state) { submit_spots } else # On-demand instance with_request_limit_backoff(state) { submit_server } end info("Instance <#{server.id}> requested.") with_request_limit_backoff(state) do logging_proc = ->(attempts) { info("Polling AWS for existence, attempt #{attempts}...") } server.wait_until_exists(before_attempt: logging_proc) end state[:server_id] = server.id info("EC2 instance <#{state[:server_id]}> created.") # See https://github.com/aws/aws-sdk-ruby/issues/859 # Waiting can fail, so we have to retry on that. Retryable.retryable( tries: 10, sleep: ->(n) { [2**n, 30].min }, on: ::Aws::EC2::Errors::InvalidInstanceIDNotFound ) do |_r, _| wait_until_ready(server, state) end info("EC2 instance <#{state[:server_id]}> ready (hostname: #{state[:hostname]}).") if config[:use_instance_connect] instance_connect_setup_ready(state) elsif config[:use_ssm_session_manager] ssm_session_manager_setup_ready(state) end instance.transport.connection(state).wait_until_ready attach_network_interface(state) unless config[:elastic_network_interface_id].nil? create_ec2_json(state) if /chef/i.match?(instance.provisioner.name) debug("ec2:create '#{state[:hostname]}'") rescue Exception => e # Clean up the instance and any auto-created security groups or keys on the way out. destroy(state) raise "#{e.message} in the specified region #{config[:region]}. Please check this AMI is available in this region." end def destroy(state) if state[:server_id] server = ec2.get_instance(state[:server_id]) unless server.nil? instance.transport.connection(state).close begin server.terminate rescue ::Aws::EC2::Errors::InvalidInstanceIDNotFound => e warn("Received #{e}, instance was probably already destroyed. Ignoring") end end # If we are going to clean up an automatic security group, we need # to wait for the instance to shut down. This slightly breaks the # subsystem encapsulation, sorry not sorry. if state[:auto_security_group_id] && server && ec2.instance_exists?(state[:server_id]) wait_log = proc do |attempts| c = attempts * config[:retryable_sleep] t = config[:retryable_tries] * config[:retryable_sleep] info "Waited #{c}/#{t}s for instance <#{server.id}> to terminate." end server.wait_until_terminated( max_attempts: config[:retryable_tries], delay: config[:retryable_sleep], before_attempt: wait_log ) end info("EC2 instance <#{state[:server_id]}> destroyed.") state.delete(:server_id) state.delete(:hostname) end # Clean up any auto-created security groups or keys. delete_security_group(state) delete_key(state) # Clean up dedicated hosts matching instance_type and unused (if allowed) return unless config[:tenancy] == "host" && allow_deallocate_host? empty_hosts = hosts_with_capacity.select { |host| host_unused?(host) } empty_hosts.each { |host| deallocate_host(host.host_id) } end def image return @image if defined?(@image) if config[:image_id] @image = ec2.resource.image(config[:image_id]) show_chosen_image else raise "Neither image_id nor an image_search specified for instance #{instance.name}!" \ " Please specify one or the other." end @image end def default_instance_type @instance_type ||= if image && image.virtualization_type == "hvm" info("instance_type not specified. Using free tier t2.micro instance ...") "t2.micro" else info("instance_type not specified. Using free tier t1.micro instance since" \ " image is paravirtual (pick an hvm image to use the superior t2.micro!) ...") "t1.micro" end end # The actual platform is the platform detected from the image def actual_platform @actual_platform ||= Aws::StandardPlatform.from_image(self, image) if image end def desired_platform @desired_platform ||= begin platform = Aws::StandardPlatform.from_platform_string(self, instance.platform.name) if platform debug("platform name #{instance.platform.name} appears to be a standard platform." \ " Searching for #{platform} ...") end platform end end def default_ami @default_ami ||= begin search_platform = desired_platform || Aws::StandardPlatform.from_platform_string(self, "ubuntu") image_search = config[:image_search] || search_platform.image_search search_platform.find_image(image_search) end end def update_username(state) # BUG: With the following equality condition on username, if the user specifies 'root' # as the transport's username then we will overwrite that value with one from the standard # platform definitions. This seems difficult to handle here as the default username is # provided by the underlying transport classes, and is often non-nil (eg; 'root'), leaving # us no way to distinguish a user-set value from the transport's default. # See https://github.com/test-kitchen/kitchen-ec2/pull/273 if actual_platform && instance.transport[:username] == instance.transport.class.defaults[:username] debug("No SSH username specified: using default username #{actual_platform.username} " \ "for image #{config[:image_id]}, which we detected as #{actual_platform}.") state[:username] = actual_platform.username end end def ec2 @ec2 ||= Aws::Client.new( config[:region], config[:shared_credentials_profile], config[:http_proxy], config[:retry_limit], config[:ssl_verify_peer] ) end def instance_generator @instance_generator = Aws::InstanceGenerator.new(config, ec2, instance.logger) end # AWS helper for creating the instance def submit_server instance_data = instance_generator.ec2_instance_data debug("Creating EC2 instance in region #{config[:region]} with properties:") instance_data.each do |key, value| debug("- #{key} = #{value.inspect}") end ec2.create_instance(instance_data) end def config return super unless @config @config end # Take one config and expand to multiple configs def expand_config(conf, key) configs = [] if conf[key].is_a?(Array) values = conf[key] values.each do |value| new_config = conf.clone new_config[key] = value configs.push new_config end else configs.push conf end configs end def submit_spots configs = [config] expanded = [] keys = %i{instance_type} if config[:subnet_filter] # => Enable cascading through matching subnets client = ::Aws::EC2::Client.new(region: config[:region]) filters = [config[:subnet_filter]].flatten r = { filters: [] } filters.each do |subnet_filter| r[:filters] << { name: "tag:#{subnet_filter[:tag]}", values: [subnet_filter[:value]], } end subnets = client.describe_subnets(r).subnets raise "Subnets with tags '#{filters}' not found!" if subnets.empty? configs = subnets.map do |subnet| new_config = config.clone new_config[:subnet_id] = subnet.subnet_id new_config[:subnet_filter] = nil new_config end else # => Use explicitly specified subnets keys << :subnet_id end keys.each do |key| configs.each do |conf| expanded.push expand_config(conf, key) end configs = expanded.flatten expanded = [] end errs = [] configs.each do |conf| @config = conf return submit_spot rescue => e errs.append(e) end raise ["Could not create a spot instance:", errs].flatten.join("\n") end def submit_spot debug("Creating EC2 Spot Instance..") instance_data = instance_generator.ec2_instance_data config_spot_price = config[:spot_price].to_s spot_price = if %w{ondemand on-demand}.include?(config_spot_price) "" else config_spot_price end spot_options = { # Must use one-time in order to use instance_interruption_behavior=terminate # spot_instance_type: "one-time", # default # Must use instance_interruption_behavior=terminate in order to use block_duration_minutes # instance_interruption_behavior: "terminate", # default } if config[:block_duration_minutes] spot_options[:block_duration_minutes] = config[:block_duration_minutes] end unless spot_price == "" # i.e. on-demand spot_options[:max_price] = spot_price end instance_data[:instance_market_options] = { market_type: "spot", spot_options:, } # The preferred way to create a spot instance is via request_spot_instances() # However, it does not allow for tagging to occur at creation time. # create_instances() allows creation of tagged spot instances, but does # not retry if the price could not be satisfied immediately. Retryable.retryable( tries: config[:spot_wait] / config[:retryable_sleep], sleep: ->(_n) { config[:retryable_sleep] }, on: ::Aws::EC2::Errors::SpotMaxPriceTooLow ) do |retries| c = retries * config[:retryable_sleep] t = config[:spot_wait] info "Waited #{c}/#{t}s for spot request to become fulfilled." ec2.create_instance(instance_data) end end # Normally we could use `server.wait_until_running` but we actually need # to check more than just the instance state def wait_until_ready(server, state) wait_with_destroy(server, state, "to become ready") do |aws_instance| hostname = hostname(aws_instance, config[:interface]) # We aggressively store the hostname so if the process fails here # we still have it, even if it will change later state[:hostname] = hostname # Euca instances often report ready before they have an IP ready = aws_instance.exists? && aws_instance.state.name == "running" && hostname != "0.0.0.0" if ready && (hostname.nil? || hostname == "") debug("Unable to detect hostname using interface_type #{config[:interface]}. Fallback to ordered mapping") state[:hostname] = hostname(aws_instance, nil) end if ready && windows_os? if instance.transport[:username] =~ /administrator/i && instance.transport[:password].nil? # If we're logging into the administrator user and a password isn't # supplied, try to fetch it from the AWS instance fetch_windows_admin_password(server, state) else output = server.console_output.output || "" unless output.nil? output = Base64.decode64(output) debug "Console output: --- \n#{output}" end ready = !!output.include?("Windows is Ready to use") end end ready end end # Poll a block, waiting for it to return true. If it does not succeed # within the configured time we destroy the instance to save people money def wait_with_destroy(server, state, status_msg, &block) wait_log = proc do |attempts| c = attempts * config[:retryable_sleep] t = config[:retryable_tries] * config[:retryable_sleep] info "Waited #{c}/#{t}s for instance <#{state[:server_id]}> #{status_msg}." end begin with_request_limit_backoff(state) do server.wait_until( max_attempts: config[:retryable_tries], delay: config[:retryable_sleep], before_attempt: wait_log, &block ) end rescue ::Aws::Waiters::Errors::WaiterFailed error("Ran out of time waiting for the server with id [#{state[:server_id]}]" \ " #{status_msg}, attempting to destroy it") destroy(state) raise end end def fetch_windows_admin_password(server, state) wait_with_destroy(server, state, "to fetch windows admin password") do |_aws_instance| enc = server.client.get_password_data( instance_id: state[:server_id] ).password_data # Password data is blank until password is available !enc.nil? && !enc.empty? end pass = with_request_limit_backoff(state) do server.decrypt_windows_password(File.expand_path(state[:ssh_key] || instance.transport[:ssh_key])) end state[:password] = pass info("Retrieved Windows password for instance <#{state[:server_id]}>.") end def with_request_limit_backoff(state) retries = 0 begin yield rescue ::Aws::EC2::Errors::RequestLimitExceeded, ::Aws::Waiters::Errors::UnexpectedError => e raise unless retries < 5 && e.message.include?("Request limit exceeded") retries += 1 info("Request limit exceeded for instance <#{state[:server_id]}>." \ " Trying again in #{retries**2} seconds.") sleep(retries**2) retry end end # # Ordered mapping from config name to Fog name. Ordered by preference # when looking up hostname. # INTERFACE_TYPES = { "dns" => "public_dns_name", "public" => "public_ip_address", "private" => "private_ip_address", "private_dns" => "private_dns_name", "id" => "id", }.freeze # # Lookup hostname of provided server. If interface_type is provided use # that interface to lookup hostname. Otherwise, try ordered list of # options. # def hostname(server, interface_type = nil) if interface_type interface_type = INTERFACE_TYPES.fetch(interface_type) do raise Kitchen::UserError, "Invalid interface [#{interface_type}]" end server.send(interface_type) else potential_hostname = nil INTERFACE_TYPES.each_value do |type| potential_hostname ||= server.send(type) # AWS returns an empty string if the dns name isn't populated yet potential_hostname = nil if potential_hostname == "" end potential_hostname end end # # Returns the sudo command to use or empty string if sudo is not configured # def sudo_command instance.provisioner[:sudo] ? instance.provisioner[:sudo_command].to_s : "" end def create_ec2_json(state) if windows_os? cmd = 'New-Item -Force C:\\chef\\ohai\\hints\\ec2.json -ItemType File' else debug "Using sudo_command='#{sudo_command}' for ohai hints" cmd = "#{sudo_command} mkdir -p /etc/chef/ohai/hints; #{sudo_command} touch /etc/chef/ohai/hints/ec2.json" end instance.transport.connection(state).execute(cmd) end def default_windows_user_data base_script = Kitchen::Util.outdent!(<<-EOH) $OSVersion = (get-itemproperty -Path "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" -Name ProductName).ProductName If($OSVersion.contains('2016') -Or $OSVersion.contains('2019') -Or $OSVersion -eq 'Windows Server Datacenter') { New-Item -ItemType Directory -Force -Path 'C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Log' $logfile='C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Log\\kitchen-ec2.log' # EC2Launch doesn't init extra disks by default C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Scripts\\InitializeDisks.ps1 } Else { New-Item -ItemType Directory -Force -Path 'C:\\Program Files\\Amazon\\Ec2ConfigService\\Logs' $logfile='C:\\Program Files\\Amazon\\Ec2ConfigService\\Logs\\kitchen-ec2.log' } # Logfile fail-safe in case the directory does not exist New-Item $logfile -Type file -Force # Allow script execution Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force #PS Remoting and & winrm.cmd basic config $enableArgs=@{Force=$true} $command=Get-Command Enable-PSRemoting if($command.Parameters.Keys -contains "skipnetworkprofilecheck"){ $enableArgs.skipnetworkprofilecheck=$true } Enable-PSRemoting @enableArgs & winrm.cmd set winrm/config '@{MaxTimeoutms="1800000"}' >> $logfile & winrm.cmd set winrm/config/winrs '@{MaxMemoryPerShellMB="1024"}' >> $logfile & winrm.cmd set winrm/config/winrs '@{MaxShellsPerUser="50"}' >> $logfile & winrm.cmd set winrm/config/winrs '@{MaxMemoryPerShellMB="1024"}' >> $logfile #Firewall Config & netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" profile=public protocol=tcp localport=5985 remoteip=localsubnet new remoteip=any >> $logfile Set-ItemProperty -Name LocalAccountTokenFilterPolicy -Path HKLM:\\software\\Microsoft\\Windows\\CurrentVersion\\Policies\\system -Value 1 EOH # Preparing custom static admin user if we defined something other than Administrator custom_admin_script = "" if instance.transport[:username] !~ /administrator/i && instance.transport[:password] custom_admin_script = Kitchen::Util.outdent!(<<-EOH) "Disabling Complex Passwords" >> $logfile $seccfg = [IO.Path]::GetTempFileName() & secedit.exe /export /cfg $seccfg >> $logfile (Get-Content $seccfg) | Foreach-Object {$_ -replace "PasswordComplexity\\s*=\\s*1", "PasswordComplexity = 0"} | Set-Content $seccfg & secedit.exe /configure /db $env:windir\\security\\new.sdb /cfg $seccfg /areas SECURITYPOLICY >> $logfile & cp $seccfg "c:\\" & del $seccfg $username="#{instance.transport[:username]}" $password="#{instance.transport[:password]}" "Creating static user: $username" >> $logfile & net.exe user /y /add $username $password >> $logfile "Adding $username to Administrators" >> $logfile & net.exe localgroup Administrators /add $username >> $logfile EOH end # Returning the fully constructed PowerShell script to user_data Kitchen::Util.outdent!(<<-EOH) #{base_script} #{custom_admin_script} EOH end def show_chosen_image # Print some debug stuff debug("Image for #{instance.name}: #{image.name}. #{image_info(image)}") if actual_platform info("Detected platform: #{actual_platform.name} version #{actual_platform.version}" \ " on #{actual_platform.architecture}. Instance Type: #{config[:instance_type]}." \ " Default username: #{actual_platform.username} (default).") else debug("No platform detected for #{image.name}.") end end def image_info(image) root_device = image.block_device_mappings .find { |b| b.device_name == image.root_device_name } volume_type = " #{root_device.ebs.volume_type}" if root_device&.ebs " Architecture: #{image.architecture}," \ " Virtualization: #{image.virtualization_type}," \ " Storage: #{image.root_device_type}#{volume_type}," \ " Created: #{image.creation_date}" end # Create a temporary security group for this instance. # # @api private # @param state [Hash] Instance state hash. # @return [void] def create_security_group(state) return if state[:auto_security_group_id] # Work out which VPC, if any, we are creating in. vpc_id = if config[:subnet_id] # Get the VPC ID for the subnet. subnets = ec2.client.describe_subnets(filters: [{ name: "subnet-id", values: [config[:subnet_id]] }]).subnets raise "Subnet #{config[:subnet_id]} not found during security group creation" if subnets.empty? subnets.first.vpc_id elsif config[:subnet_filter] filters = [config[:subnet_filter]].flatten r = { filters: [] } filters.each do |subnet_filter| r[:filters] << { name: "tag:#{subnet_filter[:tag]}", values: [subnet_filter[:value]], } end subnets = ec2.client.describe_subnets(r).subnets raise "Subnets with tags '#{filters}' not found during security group creation" if subnets.empty? subnets.first.vpc_id else # Try to check for a default VPC. vpcs = ec2.client.describe_vpcs(filters: [{ name: "isDefault", values: ["true"] }]).vpcs if vpcs.empty? # No default VPC so assume EC2-Classic ¯\_(ツ)_/¯ nil else # I don't actually know if you can have more than one default VPC? vpcs.first.vpc_id end end # Create the SG. params = { group_name: "kitchen-#{Array.new(8) { rand(36).to_s(36) }.join}", description: "Test Kitchen for #{instance.name} by #{Etc.getlogin || "nologin"} on #{Socket.gethostname}", tag_specifications: [ { resource_type: "security-group", tags: [ { key: "created-by", value: "test-kitchen", }, ], }, ], } params[:vpc_id] = vpc_id if vpc_id resp = ec2.client.create_security_group(params) state[:auto_security_group_id] = resp.group_id info("Created automatic security group #{state[:auto_security_group_id]}") debug(" in VPC #{vpc_id || "none"}") # Set up SG rules. ec2.client.authorize_security_group_ingress( group_id: state[:auto_security_group_id], # Allow SSH and WinRM (both plain and TLS). ip_permissions: [22, 3389, 5985, 5986].map do |port| { ip_protocol: "tcp", from_port: port, to_port: port, ip_ranges: Array(config[:security_group_cidr_ip]).map do |cidr_ip| { cidr_ip: } end, } end ) end # Create a temporary SSH key pair for this instance. # # @api private # @param state [Hash] Instance state hash. # @return [void] def create_key(state) return if state[:auto_key_id] # Encode a bunch of metadata into the name because that's all we can # set for a key pair. name_parts = [ instance.name.gsub(/\W/, ""), (Etc.getlogin || "nologin").gsub(/\W/, ""), Socket.gethostname.gsub(/\W/, "")[0..20], Time.now.utc.iso8601, Array.new(8) { rand(36).to_s(36) }.join, ] # In a perfect world this would generate the key locally and use ImportKey # instead for better security, but given the use case that is very likely # to rapidly exhaust local entropy by creating a lot of keys. So this is # probably fine. If you want very high security, probably don't use this # feature anyway. resp = ec2.client.create_key_pair( key_name: "kitchen-#{name_parts.join("-")}", key_type: config[:aws_ssh_key_type], tag_specifications: [ { resource_type: "key-pair", tags: [ { key: "created-by", value: "test-kitchen", }, ], }, ] ) state[:auto_key_id] = resp.key_name info("Created automatic key pair #{state[:auto_key_id]}") # Write the key out with safe permissions key_path = "#{config[:kitchen_root]}/.kitchen/#{instance.name}.pem" File.open(key_path, File::WRONLY | File::CREAT | File::EXCL, 00600) do |f| f.write(resp.key_material) end # Inject the key into the state to be used by the SSH transport, or for # the Windows password decrypt above in {#fetch_windows_admin_password}. state[:ssh_key] = key_path end def attach_network_interface(state) info("Attaching Network interface <#{config[:elastic_network_interface_id]}> with the instance <#{state[:server_id]}> .") client = ::Aws::EC2::Client.new(region: config[:region]) begin check_eni = client.describe_network_interface_attribute({ attribute: "attachment", network_interface_id: config[:elastic_network_interface_id], }) if check_eni.attachment.nil? unless state[:server_id].nil? client.attach_network_interface({ device_index: 1, instance_id: state[:server_id], network_interface_id: config[:elastic_network_interface_id], }) info("Attached Network interface <#{config[:elastic_network_interface_id]}> with the instance <#{state[:server_id]}> .") end else puts "ENI #{config[:elastic_network_interface_id]} already attached." end rescue ::Aws::EC2::Errors::InvalidNetworkInterfaceIDNotFound => e warn(e) end end # Clean up a temporary security group for this instance. # # @api private # @param state [Hash] Instance state hash. # @return [void] def delete_security_group(state) return unless state[:auto_security_group_id] info("Removing automatic security group #{state[:auto_security_group_id]}") ec2.client.delete_security_group(group_id: state[:auto_security_group_id]) state.delete(:auto_security_group_id) end # Clean up a temporary SSH key pair for this instance. # # @api private # @param state [Hash] Instance state hash. # @return [void] def delete_key(state) return unless state[:auto_key_id] info("Removing automatic key pair #{state[:auto_key_id]}") ec2.client.delete_key_pair(key_name: state[:auto_key_id]) state.delete(:auto_key_id) File.unlink("#{config[:kitchen_root]}/.kitchen/#{instance.name}.pem") end def finalize_config!(instance) super # Set up Instance Connect transport override if configured if config[:use_instance_connect] debug("[AWS EC2 Instance Connect] Setting up Instance Connect overrides") instance_connect_setup_override(instance) instance_connect_setup_inspec_override(instance) elsif config[:use_ssm_session_manager] debug("[AWS SSM Session Manager] Setting up SSM Session Manager overrides") ssm_session_manager_setup_override(instance) ssm_session_manager_setup_inspec_override(instance) end self end private def instance_connect_setup_override(instance) # Prevent double pushing of the SSH public keys return if instance.transport.respond_to?(:instance_connect_override_applied) # Store reference to driver for use in override driver_instance = self use_instance_connect = config[:use_instance_connect] # Override the transport's connection method to inject Instance Connect setup original_connection = instance.transport.method(:connection) instance.transport.define_singleton_method(:connection) do |state, &block| # Set up Instance Connect configuration before every connection if use_instance_connect # Refresh Instance Connect SSH key driver_instance.send(:instance_connect_refresh_key, state) # Configure connection mode based on endpoint availability if driver_instance.send(:instance_connect_endpoint_available?, state) # Proxy command mode - ensure ssh_proxy_command is set unless state[:ssh_proxy_command] driver_instance.send(:instance_connect_configure_ssh_proxy_command, state) end driver_instance.debug("[AWS EC2 Instance Connect] Transport using proxy command mode") else # Direct SSH mode - ensure hostname is set to public DNS driver_instance.send(:instance_connect_configure_direct_ssh, state) driver_instance.debug("[AWS EC2 Instance Connect] Transport using direct SSH mode") end end # Call original connection method original_connection.call(state, &block) end # Mark as applied to prevent double pushing of the SSH public keys instance.transport.define_singleton_method(:instance_connect_override_applied) { true } end def instance_connect_setup_inspec_override(instance) # Only apply to InSpec verifier return unless instance.verifier.name.downcase == "inspec" return if instance.verifier.respond_to?(:instance_connect_inspec_override_applied) # Store reference to driver for use in override driver_instance = self use_instance_connect = config[:use_instance_connect] # Override the verifier's call method to inject proxy command setup original_call = instance.verifier.method(:call) instance.verifier.define_singleton_method(:call) do |state| driver_instance.debug("[AWS EC2 Instance Connect] InSpec call method intercepted, connecting using kitchen-ec2 driver AWS EC2 Instance Connect") driver_instance.debug("[AWS EC2 Instance Connect] Instance ID: #{state[:server_id]}") # If using Instance Connect, set up the override just before the call if use_instance_connect && state[:server_id] # Check if we already have the override method defined unless respond_to?(:instance_connect_original_runner_options_for_ssh) # Store the original method define_singleton_method(:instance_connect_original_runner_options_for_ssh, method(:runner_options_for_ssh)) # Override runner_options_for_ssh define_singleton_method(:runner_options_for_ssh) do |config_data| # Get the original options opts = instance_connect_original_runner_options_for_ssh(config_data) # Inject Instance Connect configuration if enabled if use_instance_connect && config_data[:server_id] # Refresh Instance Connect SSH key driver_instance.send(:instance_connect_refresh_key, config_data) # Check if we should use proxy command or direct SSH if driver_instance.send(:instance_connect_endpoint_available?, config_data) # Build proxy command with the instance ID from state proxy_command = [ "aws", "ec2-instance-connect", "open-tunnel", "--instance-id", config_data[:server_id] ] # Add optional parameters if driver_instance.config[:instance_connect_endpoint_id] proxy_command += ["--instance-connect-endpoint-id", driver_instance.config[:instance_connect_endpoint_id]] end if driver_instance.config[:instance_connect_max_tunnel_duration] proxy_command += ["--max-tunnel-duration", driver_instance.config[:instance_connect_max_tunnel_duration].to_s] end if driver_instance.config[:shared_credentials_profile] proxy_command += ["--profile", driver_instance.config[:shared_credentials_profile]] end proxy_command += ["--region", driver_instance.config[:region]] opts["proxy_command"] = proxy_command.join(" ") driver_instance.info("[AWS EC2 Instance Connect] InSpec using proxy command: #{opts["proxy_command"]}") else # Direct SSH mode - ensure we're using the public DNS and proper SSH options server = driver_instance.ec2.get_instance(config_data[:server_id]) public_dns = server&.public_dns_name if public_dns && !public_dns.empty? opts["host"] = public_dns opts["ssh_options"] = (opts["ssh_options"] || {}).merge({ "IdentitiesOnly" => "yes", }) driver_instance.info("[AWS EC2 Instance Connect] InSpec using direct SSH to #{public_dns} with IdentitiesOnly=yes") else driver_instance.warn("[AWS EC2 Instance Connect] No public DNS available for direct SSH mode") end end else driver_instance.info("[AWS EC2 Instance Connect] Not configuring Instance Connect - use_instance_connect: #{use_instance_connect}, server_id present: #{!!config_data[:server_id]}") end opts end end end # Call the original method original_call.call(state) end # Mark as applied to prevent double setup instance.verifier.define_singleton_method(:instance_connect_inspec_override_applied) { true } end def instance_connect_setup_ready(state) # Determine whether to use proxy command or direct SSH based on endpoint availability if instance_connect_endpoint_available?(state) # Configure SSH proxy command if not already done instance_connect_configure_ssh_proxy_command(state) unless state[:ssh_proxy_command] info("[AWS EC2 Instance Connect] Using tunnel mode - Instance Connect endpoint available") else # Configure direct SSH with public DNS instance_connect_configure_direct_ssh(state) info("[AWS EC2 Instance Connect] Using direct SSH mode - no Instance Connect endpoint") end # Refresh Instance Connect SSH key before connection instance_connect_refresh_key(state) end def instance_connect_refresh_key(state) # Extract public key from the key that was already set up key_path = state[:ssh_key] || instance.transport[:ssh_key] return unless key_path public_key = instance_connect_extract_public_key(key_path) return unless public_key username = state[:username] || actual_platform&.username # Build AWS CLI command to send public key cmd = [ "aws", "ec2-instance-connect", "send-ssh-public-key", "--instance-id", state[:server_id], "--instance-os-user", username, "--ssh-public-key", public_key, "--region", config[:region] ] cmd += ["--profile", config[:shared_credentials_profile]] if config[:shared_credentials_profile] # Execute the command with proper shell escaping debug("[AWS EC2 Instance Connect] Refreshing SSH public key for #{state[:server_id]}") escaped_cmd = cmd.map { |arg| Shellwords.escape(arg) }.join(" ") result = `#{escaped_cmd} 2>&1` unless $?.success? warn("[AWS EC2 Instance Connect] Failed to refresh SSH key: #{result}") end end def instance_connect_configure_ssh_proxy_command(state) info("[AWS EC2 Instance Connect] Configuring proxy command mode (tunnel)") # Build the AWS CLI command for the tunnel proxy_command = [ "aws", "ec2-instance-connect", "open-tunnel", "--instance-id", state[:server_id] ] # Add optional parameters if config[:instance_connect_endpoint_id] proxy_command += ["--instance-connect-endpoint-id", config[:instance_connect_endpoint_id]] end if config[:instance_connect_max_tunnel_duration] proxy_command += ["--max-tunnel-duration", config[:instance_connect_max_tunnel_duration].to_s] end if config[:shared_credentials_profile] proxy_command += ["--profile", config[:shared_credentials_profile]] end proxy_command += ["--region", config[:region]] proxy_command_str = proxy_command.join(" ") info("Configuring SSH to use Instance Connect tunnel: #{proxy_command_str}") state[:ssh_proxy_command] = proxy_command_str # Store Instance Connect details for the transport to use state[:instance_connect_config] = { server_id: state[:server_id], username: state[:username] || actual_platform&.username, region: config[:region], profile: config[:shared_credentials_profile], tunnel_mode: true, } end def instance_connect_endpoint_available?(state) # If explicitly configured, respect that configuration return true if config[:instance_connect_endpoint_id] # Check if there are any instance connect endpoints in the VPC vpc_id = get_vpc_id_for_instance(state) return false unless vpc_id begin endpoints = ec2.client.describe_instance_connect_endpoints( filters: [ { name: "vpc-id", values: [vpc_id] }, { name: "state", values: ["create-complete"] }, ] ).instance_connect_endpoints !endpoints.empty? rescue ::Aws::EC2::Errors::InvalidAction, ::Aws::EC2::Errors::UnauthorizedOperation => e # Instance Connect endpoints may not be available in this region or account debug("[AWS EC2 Instance Connect] Cannot check for endpoints: #{e.message}") false end end def get_vpc_id_for_instance(state) # Get the instance details to find its VPC return unless state[:server_id] begin instance_info = ec2.client.describe_instances(instance_ids: [state[:server_id]]).reservations.first&.instances&.first return unless instance_info instance_info.vpc_id rescue => e debug("[AWS EC2 Instance Connect] Error getting VPC ID for instance: #{e.message}") nil end end def instance_connect_configure_direct_ssh(state) # For direct SSH, we need to ensure the hostname is the public DNS name # and configure SSH options appropriately server = ec2.get_instance(state[:server_id]) public_dns = server.public_dns_name if public_dns && !public_dns.empty? info("[AWS EC2 Instance Connect] Configuring direct SSH to #{public_dns}") state[:hostname] = public_dns # Store Instance Connect details for direct SSH mode state[:instance_connect_config] = { server_id: state[:server_id], username: state[:username] || actual_platform&.username, region: config[:region], profile: config[:shared_credentials_profile], direct_ssh: true, hostname: public_dns, } else warn("[AWS EC2 Instance Connect] No public DNS available for direct SSH, falling back to existing hostname") end end def instance_connect_extract_public_key(private_key_path) public_key_path = "#{private_key_path}.pub" if File.exist?(public_key_path) return File.read(public_key_path).strip end begin key = SSHKey.new(File.read(private_key_path)) key.ssh_public_key rescue => e raise "Unable to extract public key from #{private_key_path}: #{e.message}" end end # SSM Session Manager Support Methods def ssm_session_manager @ssm_session_manager ||= Aws::SsmSessionManager.new(config, instance.logger) end def ssm_session_manager_setup_ready(state) info("[AWS SSM Session Manager] Setting up SSM Session Manager connection") # Verify session manager plugin is installed unless ssm_session_manager.session_manager_plugin_installed? warn("[AWS SSM Session Manager] Session Manager plugin not found. Please install it from: " \ "https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html") end # Wait for SSM agent to be available max_retries = 12 retry_delay = 10 retries = 0 loop do if ssm_session_manager.ssm_agent_available?(state[:server_id]) info("[AWS SSM Session Manager] SSM agent is available on instance #{state[:server_id]}") break end retries += 1 if retries >= max_retries warn("[AWS SSM Session Manager] SSM agent did not become available after #{max_retries * retry_delay} seconds. " \ "Ensure the instance has an IAM instance profile with SSM permissions and the SSM agent is running.") break end info("[AWS SSM Session Manager] Waiting for SSM agent to be available (attempt #{retries}/#{max_retries})...") sleep retry_delay end end def ssm_session_manager_setup_override(instance) # Prevent double setup return if instance.transport.respond_to?(:ssm_session_manager_override_applied) # Store reference to driver for use in override driver_instance = self use_ssm = config[:use_ssm_session_manager] # Override the transport's connection method to inject SSM setup original_connection = instance.transport.method(:connection) instance.transport.define_singleton_method(:connection) do |state, &block| if use_ssm && state[:server_id] # Build SSM start-session command cmd = [ "aws", "ssm", "start-session", "--target", state[:server_id], "--region", driver_instance.config[:region] ] # Add document name if specified if driver_instance.config[:ssm_session_manager_document_name] cmd += ["--document-name", driver_instance.config[:ssm_session_manager_document_name]] end # Add AWS profile if specified if driver_instance.config[:shared_credentials_profile] cmd += ["--profile", driver_instance.config[:shared_credentials_profile]] end proxy_command = cmd.join(" ") driver_instance.info("[AWS SSM Session Manager] Using proxy command: #{proxy_command}") # Set proxy command for SSH transport state[:ssh_proxy_command] = proxy_command end # Call original connection method original_connection.call(state, &block) end # Mark as applied instance.transport.define_singleton_method(:ssm_session_manager_override_applied) { true } end def ssm_session_manager_setup_inspec_override(instance) # Only apply to InSpec verifier return unless instance.verifier.name.downcase == "inspec" return if instance.verifier.respond_to?(:ssm_session_manager_inspec_override_applied) # Store reference to driver for use in override driver_instance = self use_ssm = config[:use_ssm_session_manager] # Override the verifier's call method to inject SSM setup original_call = instance.verifier.method(:call) instance.verifier.define_singleton_method(:call) do |state| driver_instance.debug("[AWS SSM Session Manager] InSpec call method intercepted") # Set up SSM for InSpec if enabled if use_ssm && state[:server_id] # Check if we already have the override method defined unless respond_to?(:ssm_original_runner_options_for_ssh) # Store the original method define_singleton_method(:ssm_original_runner_options_for_ssh, method(:runner_options_for_ssh)) # Override runner_options_for_ssh define_singleton_method(:runner_options_for_ssh) do |config_data| # Get the original options opts = ssm_original_runner_options_for_ssh(config_data) # Inject SSM Session Manager configuration if enabled if use_ssm && config_data[:server_id] # Build SSM start-session command cmd = [ "aws", "ssm", "start-session", "--target", config_data[:server_id], "--region", driver_instance.config[:region] ] # Add document name if specified if driver_instance.config[:ssm_session_manager_document_name] cmd += ["--document-name", driver_instance.config[:ssm_session_manager_document_name]] end # Add AWS profile if specified if driver_instance.config[:shared_credentials_profile] cmd += ["--profile", driver_instance.config[:shared_credentials_profile]] end opts["proxy_command"] = cmd.join(" ") driver_instance.info("[AWS SSM Session Manager] InSpec using proxy command: #{opts["proxy_command"]}") end opts end end end # Call the original method original_call.call(state) end # Mark as applied instance.verifier.define_singleton_method(:ssm_session_manager_inspec_override_applied) { true } end end end end ================================================ FILE: lib/kitchen/driver/ec2_version.rb ================================================ # # Author:: Fletcher Nichol () # # Copyright:: Chef Software, Inc. # Copyright:: 2012-2018, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Kitchen module Driver # Version string for EC2 Test Kitchen driver EC2_VERSION = "3.22.3".freeze end end ================================================ FILE: release-please-config.json ================================================ { "packages": { ".": { "package-name": "kitchen-ec2", "changelog-path": "CHANGELOG.md", "release-type": "ruby", "include-component-in-tag": false, "version-file": "lib/kitchen/driver/ec2_version.rb" } }, "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json" } ================================================ FILE: renovate.json ================================================ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:recommended", ":disableDependencyDashboard", "schedule:automergeEarlyMondays" ] } ================================================ FILE: spec/kitchen/driver/aws/client_spec.rb ================================================ # # Author:: Tyler Ball () # # Copyright:: 2015-2018, Fletcher Nichol # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "kitchen/driver/aws/client" describe Kitchen::Driver::Aws::Client do let(:client) { Kitchen::Driver::Aws::Client.new("us-west-1") } describe "#initialize" do it "successfully creates a client" do expect(client).to be_a(Kitchen::Driver::Aws::Client) end it "Sets the AWS config" do client expect(Aws.config[:region]).to eq("us-west-1") end context "when provided all optional parameters" do let(:client) do Kitchen::Driver::Aws::Client.new( "us-west-1", "test-profile", "http_proxy", 999, false ) end it "Sets the AWS config" do client expect(Aws.config[:region]).to eq("us-west-1") expect(Aws.config[:profile]).to eq("test-profile") expect(Aws.config[:http_proxy]).to eq("http_proxy") expect(Aws.config[:retry_limit]).to eq(999) expect(Aws.config[:ssl_verify_peer]).to eq(false) end end end it "returns a client" do expect(client.client).to be_a(Aws::EC2::Client) end it "returns a resource" do expect(client.resource).to be_a(Aws::EC2::Resource) end end ================================================ FILE: spec/kitchen/driver/aws/image_selection_spec.rb ================================================ # # Copyright:: 2015-2018, Fletcher Nichol # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "kitchen/driver/ec2" require "kitchen/provisioner/dummy" require "kitchen/transport/dummy" require "kitchen/verifier/dummy" describe "Default images for various platforms" do let(:driver) do Kitchen::Driver::Ec2.new(region: "us-west-2", aws_ssh_key_id: "foo", **config) end let(:config) { {} } let(:state_file) { {} } def new_instance(platform_name: "blarghle") Kitchen::Instance.new( driver: driver, suite: Kitchen::Suite.new(name: "suite-name"), platform: Kitchen::Platform.new(name: platform_name), provisioner: Kitchen::Provisioner::Dummy.new, transport: Kitchen::Transport::Dummy.new, verifier: Kitchen::Verifier::Dummy.new, state_file: Kitchen::StateFile.new("/nonexistent", "suite-name-#{platform_name}"), lifecycle_hooks: Kitchen::LifecycleHooks.new(config, state_file) ) end PLATFORM_SEARCHES = { "alma" => [ { name: "owner-id", values: %w{764336703387} }, { name: "name", values: ["AlmaLinux OS *"] }, ], "alma-8" => [ { name: "owner-id", values: %w{764336703387} }, { name: "name", values: ["AlmaLinux OS 8*"] }, ], "alma-9" => [ { name: "owner-id", values: %w{764336703387} }, { name: "name", values: ["AlmaLinux OS 9*"] }, ], "alma-arm64" => [ { name: "owner-id", values: %w{764336703387} }, { name: "name", values: ["AlmaLinux OS *"] }, { name: "architecture", values: %w{arm64} }, ], "alma-x86_64" => [ { name: "owner-id", values: %w{764336703387} }, { name: "name", values: ["AlmaLinux OS *"] }, { name: "architecture", values: %w{x86_64} }, ], "alma-8-arm64" => [ { name: "owner-id", values: %w{764336703387} }, { name: "name", values: ["AlmaLinux OS 8*"] }, { name: "architecture", values: %w{arm64} }, ], "alma-8-x86_64" => [ { name: "owner-id", values: %w{764336703387} }, { name: "name", values: ["AlmaLinux OS 8*"] }, { name: "architecture", values: %w{x86_64} }, ], "amazon" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn-ami-*} }, ], "amazon-x86_64" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn-ami-*} }, { name: "architecture", values: ["x86_64"] }, ], "amazon-2016" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn-ami-*-2016*} }, ], "amazon-2017" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn-ami-*-2017*} }, ], "amazon-2016.09" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn-ami-*-2016.09*} }, ], "amazon-2017.03" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn-ami-*-2017.03*} }, ], "amazon-2017.03-x86_64" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn-ami-*-2017.03*} }, { name: "architecture", values: ["x86_64"] }, ], "amazon2" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn2-ami-hvm-2.0.*} }, ], "amazon2-2018" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{amzn2-ami-hvm-2.0.2018*} }, ], "amazon2023" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{al2023-ami-2023.*} }, ], "amazon2023-x86_64" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{al2023-ami-2023.*} }, { name: "architecture", values: %w{x86_64} }, ], "amazon2023-arm64" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{al2023-ami-2023.*} }, { name: "architecture", values: %w{arm64} }, ], "amazon2023-11.20260413.0" => [ { name: "owner-id", values: %w{137112412989} }, { name: "name", values: %w{al2023-ami-2023.11.20260413.0*} }, ], "centos" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: ["CentOS *", "CentOS-*-GA-*", "CentOS Linux *", "CentOS Stream *"] }, ], "centos-10" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: ["CentOS 10*", "CentOS-10*-GA-*", "CentOS Linux 10*", "CentOS Stream 10*"] }, ], "centos-9" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: ["CentOS 9*", "CentOS-9*-GA-*", "CentOS Linux 9*", "CentOS Stream 9*"] }, ], "centos-8" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: ["CentOS 8*", "CentOS-8*-GA-*", "CentOS Linux 8*", "CentOS Stream 8*"] }, ], "centos-7" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: ["CentOS 7*", "CentOS-7*-GA-*", "CentOS Linux 7*", "CentOS Stream 7*"] }, ], "centos-x86_64" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: ["CentOS *", "CentOS-*-GA-*", "CentOS Linux *", "CentOS Stream *"] }, { name: "architecture", values: %w{x86_64} }, ], "centos-7-x86_64" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: ["CentOS 7*", "CentOS-7*-GA-*", "CentOS Linux 7*", "CentOS Stream 7*"] }, { name: "architecture", values: %w{x86_64} }, ], "debian" => [ { name: "owner-id", values: %w{136693071363} }, { name: "name", values: %w{debian-13-*} }, ], "debian-13" => [ { name: "owner-id", values: %w{136693071363} }, { name: "name", values: %w{debian-13-*} }, ], "debian-12" => [ { name: "owner-id", values: %w{136693071363} }, { name: "name", values: %w{debian-12-*} }, ], "debian-11" => [ { name: "owner-id", values: %w{136693071363} }, { name: "name", values: %w{debian-11-*} }, ], "debian-10" => [ { name: "owner-id", values: %w{136693071363} }, { name: "name", values: %w{debian-10-*} }, ], "debian-9" => [ { name: "owner-id", values: %w{379101102735} }, { name: "name", values: %w{debian-stretch-*} }, ], "debian-9.6" => [ { name: "owner-id", values: %w{379101102735} }, { name: "name", values: %w{debian-stretch-*} }, ], "debian-x86_64" => [ { name: "owner-id", values: %w{136693071363} }, { name: "name", values: %w{debian-13-*} }, { name: "architecture", values: %w{x86_64} }, ], "rhel" => [ { name: "owner-id", values: %w{309956199498} }, { name: "name", values: %w{RHEL-*} }, ], "rhel-6" => [ { name: "owner-id", values: %w{309956199498} }, { name: "name", values: %w{RHEL-6*} }, ], "rhel-7.1" => [ { name: "owner-id", values: %w{309956199498} }, { name: "name", values: %w{RHEL-7.1*} }, ], "rhel-x86_64" => [ { name: "owner-id", values: %w{309956199498} }, { name: "name", values: %w{RHEL-*} }, { name: "architecture", values: %w{x86_64} }, ], "rhel-6-x86_64" => [ { name: "owner-id", values: %w{309956199498} }, { name: "name", values: %w{RHEL-6*} }, { name: "architecture", values: %w{x86_64} }, ], "rocky" => [ { name: "owner-id", values: %w{792107900819} }, { name: "name", values: ["Rocky-*"] }, ], "rocky-8" => [ { name: "owner-id", values: %w{792107900819} }, { name: "name", values: ["Rocky-8-*"] }, ], "rocky-9" => [ { name: "owner-id", values: %w{792107900819} }, { name: "name", values: ["Rocky-9-*"] }, ], "rocky-arm64" => [ { name: "owner-id", values: %w{792107900819} }, { name: "name", values: ["Rocky-*"] }, { name: "architecture", values: %w{arm64} }, ], "rocky-x86_64" => [ { name: "owner-id", values: %w{792107900819} }, { name: "name", values: ["Rocky-*"] }, { name: "architecture", values: %w{x86_64} }, ], "rocky-8-arm64" => [ { name: "owner-id", values: %w{792107900819} }, { name: "name", values: ["Rocky-8-*"] }, { name: "architecture", values: %w{arm64} }, ], "rocky-8-x86_64" => [ { name: "owner-id", values: %w{792107900819} }, { name: "name", values: ["Rocky-8-*"] }, { name: "architecture", values: %w{x86_64} }, ], "el" => [ { name: "owner-id", values: %w{309956199498} }, { name: "name", values: %w{RHEL-*} }, ], "el-6-x86_64" => [ { name: "owner-id", values: %w{309956199498} }, { name: "name", values: %w{RHEL-6*} }, { name: "architecture", values: %w{x86_64} }, ], "fedora" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: %w{Fedora-Cloud-Base-*} }, ], "fedora-22" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: %w{Fedora-Cloud-Base-22-*} }, ], "fedora-x86_64" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: %w{Fedora-Cloud-Base-*} }, { name: "architecture", values: %w{x86_64} }, ], "fedora-22-x86_64" => [ { name: "owner-id", values: %w{125523088429} }, { name: "name", values: %w{Fedora-Cloud-Base-22-*} }, { name: "architecture", values: %w{x86_64} }, ], "freebsd" => [ { name: "owner-id", values: %w{118940168514} }, { name: "name", values: ["FreeBSD *-RELEASE*", "FreeBSD/EC2 *-RELEASE*"] }, ], "freebsd-10" => [ { name: "owner-id", values: %w{118940168514} }, { name: "name", values: ["FreeBSD 10*-RELEASE*", "FreeBSD/EC2 10*-RELEASE*"] }, ], "freebsd-10.1" => [ { name: "owner-id", values: %w{118940168514} }, { name: "name", values: ["FreeBSD 10.1*-RELEASE*", "FreeBSD/EC2 10.1*-RELEASE*"] }, ], "freebsd-x86_64" => [ { name: "owner-id", values: %w{118940168514} }, { name: "name", values: ["FreeBSD *-RELEASE*", "FreeBSD/EC2 *-RELEASE*"] }, { name: "architecture", values: %w{x86_64} }, ], "freebsd-10-x86_64" => [ { name: "owner-id", values: %w{118940168514} }, { name: "name", values: ["FreeBSD 10*-RELEASE*", "FreeBSD/EC2 10*-RELEASE*"] }, { name: "architecture", values: %w{x86_64} }, ], "macos-12.5" => [ { name: "owner-id", values: %w{100343932686} }, { name: "name", values: %w{amzn-ec2-macos-12.5*} }, ], "macos-12.6-arm64" => [ { name: "owner-id", values: %w{100343932686} }, { name: "name", values: %w{amzn-ec2-macos-12.6*} }, { name: "architecture", values: %w{arm64_mac} }, ], "ubuntu" => [ { name: "owner-id", values: %w{099720109477} }, { name: "name", values: %w{ubuntu/images/*/ubuntu-*-*} }, ], "ubuntu-14" => [ { name: "owner-id", values: %w{099720109477} }, { name: "name", values: %w{ubuntu/images/*/ubuntu-*-14*} }, ], "ubuntu-12.04" => [ { name: "owner-id", values: %w{099720109477} }, { name: "name", values: %w{ubuntu/images/*/ubuntu-*-12.04*} }, ], "ubuntu-x86_64" => [ { name: "owner-id", values: %w{099720109477} }, { name: "name", values: %w{ubuntu/images/*/ubuntu-*-*} }, { name: "architecture", values: %w{x86_64} }, ], "ubuntu-14-x86_64" => [ { name: "owner-id", values: %w{099720109477} }, { name: "name", values: %w{ubuntu/images/*/ubuntu-*-14*} }, { name: "architecture", values: %w{x86_64} }, ], "windows" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-*-RTM-English-*-Base-* Windows_Server-*-SP*-English-*-Base-* Windows_Server-*-R*_RTM-English-*-Base-* Windows_Server-*-R*_SP*-English-*-Base-* Windows_Server-*-English-Full-Base-*} }, ], "windows-2008" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2008-RTM-English-*-Base-* Windows_Server-2008-SP*-English-*-Base-*} }, ], "windows-2012" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-RTM-English-*-Base-* Windows_Server-2012-SP*-English-*-Base-*} }, ], "windows-2012r2" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-R2_RTM-English-*-Base-* Windows_Server-2012-R2_SP*-English-*-Base-*} }, ], "windows-2012sp1" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-SP1-English-*-Base-*} }, ], "windows-2012rtm" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-RTM-English-*-Base-*} }, ], "windows-2012r2sp1" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-R2_SP1-English-*-Base-*} }, ], "windows-2012r2rtm" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-R2_RTM-English-*-Base-*} }, ], "windows-x86_64" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-*-RTM-English-*-Base-* Windows_Server-*-SP*-English-*-Base-* Windows_Server-*-R*_RTM-English-*-Base-* Windows_Server-*-R*_SP*-English-*-Base-* Windows_Server-*-English-Full-Base-*} }, { name: "architecture", values: %w{x86_64} }, ], "windows-2012r2-x86_64" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-R2_RTM-English-*-Base-* Windows_Server-2012-R2_SP*-English-*-Base-*} }, { name: "architecture", values: %w{x86_64} }, ], "windows-server" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-*-RTM-English-*-Base-* Windows_Server-*-SP*-English-*-Base-* Windows_Server-*-R*_RTM-English-*-Base-* Windows_Server-*-R*_SP*-English-*-Base-* Windows_Server-*-English-Full-Base-*} }, ], "windows-server-2012r2-x86_64" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2012-R2_RTM-English-*-Base-* Windows_Server-2012-R2_SP*-English-*-Base-*} }, { name: "architecture", values: %w{x86_64} }, ], "windows-2016" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2016-English-Full-Base-*} }, ], "windows-2019" => [ { name: "owner-alias", values: %w{amazon} }, { name: "name", values: %w{ Windows_Server-2019-English-Full-Base-*} }, ], }.freeze describe "Platform defaults" do PLATFORM_SEARCHES.each do |platform_name, filters| context "when platform is #{platform_name}" do let(:image) { FakeImage.new(name: platform_name.split("-", 2)[0]) } it "searches for #{filters} and uses the resulting image" do expect(driver.ec2.resource) .to receive(:images).with(filters: filters).and_return([image]) expect(driver.ec2.resource) .to receive(:image).with(image.id).and_return(image) instance = new_instance(platform_name: platform_name) expect(instance.driver.instance_generator.ec2_instance_data[:image_id]) .to eq image.id end end end end context "when image_search is provided" do let(:image) { FakeImage.new(name: "ubuntu") } let(:config) { { image_search: { name: "SuperImage" } } } context "and platform.name is a well known platform name" do it "searches for an image id without using the standard filters" do expect(driver.ec2.resource) .to receive(:images) .with(filters: [{ name: "name", values: %w{SuperImage} }]) .and_return([image]) expect(driver.ec2.resource) .to receive(:image).with(image.id).and_return(image) instance = new_instance(platform_name: "ubuntu") expect(instance.driver.instance_generator.ec2_instance_data[:image_id]) .to eq image.id end end context "and platform.name is not a well known platform name" do let(:image) { FakeImage.new(name: "ubuntu") } it "does not search for (or find) an image, and informs the user they need to set image_id" do expect(driver.ec2.resource) .to receive(:images) .with(filters: [{ name: "name", values: %w{SuperImage} }]) .and_return([image]) expect(driver.ec2.resource) .to receive(:image).with(image.id).and_return(image) instance = new_instance(platform_name: "blarghle") expect(instance.driver.instance_generator.ec2_instance_data[:image_id]).to eq image.id end end end end ================================================ FILE: spec/kitchen/driver/aws/instance_connect_test.rb ================================================ # # Author:: Alex Kokkinos # # Copyright:: 2025, Alex Kokkinos # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t his file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "kitchen/driver/aws/instance_connect" describe Kitchen::Driver::Aws::InstanceConnect do let(:config) do { region: "us-east-1", availability_zone: "us-east-1a" } end let(:logger) { instance_double("Logger") } let(:aws_client) { instance_double("Aws::EC2InstanceConnect::Client") } let(:instance_connect) { described_class.new(config, logger) } before do allow(::Aws::EC2InstanceConnect::Client).to receive(:new).and_return(aws_client) allow(logger).to receive(:info) allow(logger).to receive(:debug) end describe "#initialize" do it "sets config and logger instance variables" do expect(instance_connect.instance_variable_get(:@config)).to eq(config) expect(instance_connect.instance_variable_get(:@logger)).to eq(logger) end it "creates AWS EC2InstanceConnect client with correct region" do expect(::Aws::EC2InstanceConnect::Client).to have_received(:new) .with(region: "us-east-1") end end describe "#send_ssh_public_key" do let(:instance_id) { "i-1234567890abcdef0" } let(:username) { "ec2-user" } let(:public_key) { "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ..." } before do allow(aws_client).to receive(:send_ssh_public_key) end it "logs info message with instance details" do expect(logger).to receive(:info) .with("Sending SSH public key to instance #{instance_id} for user #{username}") instance_connect.send_ssh_public_key(instance_id, username, public_key) end it "calls AWS client with correct parameters" do expected_params = { instance_id: instance_id, instance_os_user: username, ssh_public_key: public_key, availability_zone: "us-east-1a" } expect(aws_client).to receive(:send_ssh_public_key).with(expected_params) instance_connect.send_ssh_public_key(instance_id, username, public_key) end it "logs debug message on successful completion" do expect(logger).to receive(:debug) .with("SSH public key successfully sent to instance") instance_connect.send_ssh_public_key(instance_id, username, public_key) end it "completes the full workflow" do expect(logger).to receive(:info).ordered expect(aws_client).to receive(:send_ssh_public_key).ordered expect(logger).to receive(:debug).ordered instance_connect.send_ssh_public_key(instance_id, username, public_key) end end end ================================================ FILE: spec/kitchen/driver/aws/instance_generator_spec.rb ================================================ # # Author:: Tyler Ball () # # Copyright:: 2015-2018, Fletcher Nichol # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "kitchen/driver/aws/instance_generator" require "kitchen/driver/aws/client" require "tempfile" unless defined?(Tempfile) require "base64" unless defined?(Base64) require "aws-sdk-ec2" describe Kitchen::Driver::Aws::InstanceGenerator do let(:config) { { region: "us-east-1" } } let(:resource) { instance_double(Aws::EC2::Resource) } let(:ec2) { instance_double(Kitchen::Driver::Aws::Client, resource: resource) } let(:logger) { instance_double(Logger) } let(:generator) { Kitchen::Driver::Aws::InstanceGenerator.new(config, ec2, logger) } describe "#prepared_user_data" do context "when config[:user_data] is a file" do let(:tmp_file) { Tempfile.new("prepared_user_data_test") } let(:config) { { user_data: tmp_file.path } } before do tmp_file.write("foo\nbar") tmp_file.rewind end after do tmp_file.close tmp_file.unlink end it "reads the file contents" do expect(Base64.decode64(generator.prepared_user_data)).to eq("foo\nbar") end it "memoizes the file contents" do decoded = Base64.decode64(generator.prepared_user_data) expect(decoded).to eq("foo\nbar") tmp_file.write("other\nvalue") tmp_file.rewind expect(decoded).to eq("foo\nbar") end end context "when config[:user_data] is binary" do let(:config) { { user_data: "foo\0bar" } } it "handles nulls in user_data" do expect(Base64.decode64(generator.prepared_user_data)).to eq "foo\0bar" end end end describe "#ec2_instance_data" do ec2_stub = Aws::EC2::Client.new(stub_responses: true) ec2_stub.stub_responses( :describe_subnets, subnets: [ { subnet_id: "s-123", vpc_id: "vpc-456", tags: [{ key: "foo", value: "bar" }], }, ] ) ec2_stub.stub_responses( :describe_security_groups, security_groups: [ { group_id: "sg-123", tags: [{ key: "foo", value: "bar" }], }, ] ) it "returns empty on nil" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, max_count: 1, min_count: 1 ) end context "when populated with minimum requirements" do let(:config) do { region: "us-east-1", instance_type: "micro", ebs_optimized: true, image_id: "ami-123", subnet_id: "s-456", private_ip_address: "0.0.0.0", } end it "returns the minimum data" do expect(generator.ec2_instance_data).to eq( instance_type: "micro", ebs_optimized: true, image_id: "ami-123", key_name: nil, subnet_id: "s-456", private_ip_address: "0.0.0.0", max_count: 1, min_count: 1 ) end end context "when provided with tags" do let(:config) do { region: "us-east-2", tags: { string_tag: "string", integer_tag: 1, }, } end it "includes tag specifications" do expect(generator.ec2_instance_data).to include( tag_specifications: [ { resource_type: "instance", tags: [ { key: :string_tag, value: "string" }, { key: :integer_tag, value: "1" }, ], }, { resource_type: "volume", tags: [ { key: :string_tag, value: "string" }, { key: :integer_tag, value: "1" }, ], }, ] ) end end context "when populated with ssh key" do let(:config) do { region: "us-east-1", instance_type: "micro", ebs_optimized: true, image_id: "ami-123", aws_ssh_key_id: "key", subnet_id: "s-456", private_ip_address: "0.0.0.0", } end it "returns the minimum data" do expect(generator.ec2_instance_data).to eq( instance_type: "micro", ebs_optimized: true, image_id: "ami-123", key_name: "key", subnet_id: "s-456", private_ip_address: "0.0.0.0", max_count: 1, min_count: 1 ) end end context "when provided subnet tag instead of id" do let(:config) do { instance_type: "micro", ebs_optimized: true, image_id: "ami-123", aws_ssh_key_id: "key", subnet_id: nil, region: "us-west-2", subnet_filter: { tag: "foo", value: "bar", }, } end it "generates id from the provided tag" do allow(Aws::EC2::Client).to receive(:new).and_return(ec2_stub) expect(ec2_stub).to receive(:describe_subnets).with( { filters: [ { name: "tag:foo", values: ["bar"], }, ], } ).and_return(ec2_stub.describe_subnets) expect(generator.ec2_instance_data[:subnet_id]).to eq("s-123") end end context "when provided security_group tag instead of id" do let(:config) do { instance_type: "micro", ebs_optimized: true, image_id: "ami-123", aws_ssh_key_id: "key", subnet_id: "s-123", security_group_ids: nil, region: "us-west-2", security_group_filter: { tag: "foo", value: "bar", }, } end it "generates id from the provided tag" do allow(Aws::EC2::Client).to receive(:new).and_return(ec2_stub) expect(ec2_stub).to receive(:describe_security_groups).with( { filters: [ { name: "tag:foo", values: ["bar"], }, { name: "vpc-id", values: ["vpc-456"], }, ], } ).and_return(ec2_stub.describe_security_groups) expect(generator.ec2_instance_data[:security_group_ids]).to eq(["sg-123"]) end end context "when provided a non existing security_group tag filter" do ec2_stub_without_security_group = Aws::EC2::Client.new(stub_responses: true) ec2_stub_without_security_group.stub_responses( :describe_subnets, subnets: [ { subnet_id: "s-123", vpc_id: "vpc-456", tags: [{ key: "foo", value: "bar" }], }, ] ) let(:config) do { instance_type: "micro", ebs_optimized: true, image_id: "ami-123", aws_ssh_key_id: "key", subnet_id: "s-123", security_group_ids: nil, region: "us-west-2", security_group_filter: { tag: "foo", value: "bar", }, } end it "generates id from the provided tag" do allow(Aws::EC2::Client).to receive(:new).and_return(ec2_stub_without_security_group) expect(ec2_stub_without_security_group).to receive(:describe_security_groups).with( { filters: [ { name: "tag:foo", values: ["bar"], }, { name: "vpc-id", values: ["vpc-456"], }, ], } ).and_return(ec2_stub_without_security_group.describe_security_groups) expect { generator.ec2_instance_data }.to raise_error( "A Security Group matching the following filter could not be found:\n#{config[:security_group_filter]}" ) end end context "when passed an empty block_device_mappings" do let(:config) do { region: "us-east-1", instance_type: "micro", ebs_optimized: true, image_id: "ami-123", aws_ssh_key_id: "key", subnet_id: "s-456", private_ip_address: "0.0.0.0", block_device_mappings: [], } end it "does not return block_device_mappings" do expect(generator.ec2_instance_data).to eq( instance_type: "micro", ebs_optimized: true, image_id: "ami-123", key_name: "key", subnet_id: "s-456", private_ip_address: "0.0.0.0", max_count: 1, min_count: 1 ) end end context "when availability_zone is provided as 'eu-west-1c'" do let(:config) do { region: "eu-east-1", availability_zone: "eu-west-1c", } end it "returns that in the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, placement: { availability_zone: "eu-west-1c" }, max_count: 1, min_count: 1 ) end end context "when availability_zone is provided as 'c'" do let(:config) do { region: "eu-east-1", availability_zone: "c", } end it "adds the region to it in the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, placement: { availability_zone: "eu-east-1c" }, max_count: 1, min_count: 1 ) end end context "when availability_zone is not provided" do let(:config) do { region: "eu-east-1", } end it "is not added to the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, max_count: 1, min_count: 1 ) end end context "when availability_zone and tenancy are provided" do let(:config) do { region: "eu-east-1", availability_zone: "c", tenancy: "dedicated", } end it "adds the region to it in the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, max_count: 1, min_count: 1, placement: { availability_zone: "eu-east-1c", tenancy: "dedicated" } ) end end context "when tenancy is provided but availability_zone isn't" do let(:config) do { region: "eu-east-1", tenancy: "default", } end it "is not added to the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, placement: { tenancy: "default" }, max_count: 1, min_count: 1 ) end end context "when availability_zone and tenancy are provided" do let(:config) do { region: "eu-east-1", availability_zone: "c", tenancy: "dedicated", } end it "adds the region to it in the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, max_count: 1, min_count: 1, placement: { availability_zone: "eu-east-1c", tenancy: "dedicated" } ) end end context "when tenancy is provided but availability_zone isn't" do let(:config) do { region: "eu-east-1", tenancy: "default", } end it "is not added to the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, placement: { tenancy: "default" }, max_count: 1, min_count: 1 ) end end context "when subnet_id is provided" do let(:config) do { region: "us-east-1", subnet_id: "s-456", } end it "adds a network_interfaces block" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: "s-456", private_ip_address: nil, max_count: 1, min_count: 1 ) end end context "when associate_public_ip is provided" do let(:config) do { region: "us-east-1", associate_public_ip: true, } end it "adds a network_interfaces block" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, network_interfaces: [{ device_index: 0, associate_public_ip_address: true, delete_on_termination: true, }], max_count: 1, min_count: 1 ) end context "and associate_ipv6 is provided" do let(:config) do { region: "us-east-1", associate_public_ip: true, associate_ipv6: true, } end it "adds a network_interfaces block" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, network_interfaces: [{ device_index: 0, associate_public_ip_address: true, ipv_6_address_count: 1, delete_on_termination: true, }], max_count: 1, min_count: 1 ) end end context "and subnet is provided" do let(:config) do { region: "us-east-1", associate_public_ip: true, subnet_id: "s-456", } end it "adds a network_interfaces block" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, private_ip_address: nil, network_interfaces: [{ device_index: 0, associate_public_ip_address: true, delete_on_termination: true, subnet_id: "s-456", }], max_count: 1, min_count: 1 ) end end context "and security_group_ids is provided" do let(:config) do { region: "us-east-1", associate_public_ip: true, security_group_ids: ["sg-789"], } end it "adds a network_interfaces block" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, network_interfaces: [{ device_index: 0, associate_public_ip_address: true, delete_on_termination: true, groups: ["sg-789"], }], max_count: 1, min_count: 1 ) end it "accepts a single string value" do config[:security_group_ids] = "only-one" expect(generator.ec2_instance_data).to include( network_interfaces: [{ device_index: 0, associate_public_ip_address: true, delete_on_termination: true, groups: ["only-one"], }] ) end end context "and private_ip_address is provided" do let(:config) do { region: "us-east-1", associate_public_ip: true, private_ip_address: "0.0.0.0", } end it "adds a network_interfaces block" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, network_interfaces: [{ device_index: 0, associate_public_ip_address: true, delete_on_termination: true, private_ip_address: "0.0.0.0", }], max_count: 1, min_count: 1 ) end end end context "when placement host resource group arn and licenses are provided" do let(:config) do { region: "eu-east-1", placement: { host_resource_group_arn: "arn:aws:ec2:us-east-1:123456789012:resource-group/my-group", }, licenses: [ { license_configuration_arn: "arn:aws:ec2:us-east-1:123456789012:license-configuration/my-license", } ], } end it "adds the region to it in the instance data" do expect(generator.ec2_instance_data).to eq( instance_type: nil, ebs_optimized: nil, image_id: nil, key_name: nil, subnet_id: nil, private_ip_address: nil, max_count: 1, min_count: 1, placement: { host_resource_group_arn: "arn:aws:ec2:us-east-1:123456789012:resource-group/my-group"}, licenses: [{license_configuration_arn: "arn:aws:ec2:us-east-1:123456789012:license-configuration/my-license"}] ) end end context "when provided the maximum config" do let(:config) do { region: "eu-west-1", availability_zone: "eu-west-1a", instance_type: "micro", ebs_optimized: true, image_id: "ami-123", aws_ssh_key_id: "key", subnet_id: "s-456", private_ip_address: "0.0.0.0", block_device_mappings: [ { device_name: "/dev/sda2", virtual_name: "test", ebs: { volume_size: 15, delete_on_termination: false, volume_type: "gp2", snapshot_id: "id", }, }, ], security_group_ids: ["sg-789"], user_data: "foo", iam_profile_name: "iam-123", associate_public_ip: true, tags: { string_tag: "string", integer_tag: 1, }, licenses: [{ license_configuration_arn: "arn:aws:ec2:us-east-1:123456789012:license-configuration/my-license", }], placement: { availability_zone: "eu-west-1a", tenancy: "dedicated" }, } end it "returns the maximum data" do expect(generator.ec2_instance_data).to eq( instance_type: "micro", ebs_optimized: true, image_id: "ami-123", key_name: "key", block_device_mappings: [ { device_name: "/dev/sda2", virtual_name: "test", ebs: { volume_size: 15, delete_on_termination: false, volume_type: "gp2", snapshot_id: "id", }, }, ], iam_instance_profile: { name: "iam-123" }, licenses: [{ license_configuration_arn: "arn:aws:ec2:us-east-1:123456789012:license-configuration/my-license", }], network_interfaces: [{ device_index: 0, associate_public_ip_address: true, subnet_id: "s-456", delete_on_termination: true, groups: ["sg-789"], private_ip_address: "0.0.0.0", }], placement: { availability_zone: "eu-west-1a", tenancy: "dedicated" }, user_data: Base64.encode64("foo"), max_count: 1, min_count: 1, tag_specifications: [ { resource_type: "instance", tags: [ { key: :string_tag, value: "string" }, { key: :integer_tag, value: "1" }, ], }, { resource_type: "volume", tags: [ { key: :string_tag, value: "string" }, { key: :integer_tag, value: "1" }, ], }, ] ) end end end end ================================================ FILE: spec/kitchen/driver/aws/ssm_session_manager_spec.rb ================================================ # # Author:: GitHub Copilot # # Copyright:: 2025, GitHub # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'kitchen/driver/aws/ssm_session_manager' describe Kitchen::Driver::Aws::SsmSessionManager do let(:config) do { region: 'us-west-2', shared_credentials_profile: nil, } end let(:logger) { instance_double(Logger, debug: nil, info: nil, warn: nil) } let(:ssm_client) { instance_double(Aws::SSM::Client) } let(:ssm_manager) { described_class.new(config, logger) } before do allow(Aws::SSM::Client).to receive(:new).and_return(ssm_client) end describe '#ssm_agent_available?' do let(:instance_id) { 'i-1234567890abcdef0' } context 'when SSM agent is online' do it 'returns true' do response = double( instance_information_list: [ double(ping_status: 'Online'), ] ) expect(ssm_client).to receive(:describe_instance_information) .with(filters: [{ key: 'InstanceIds', values: [instance_id] }]) .and_return(response) expect(ssm_manager.ssm_agent_available?(instance_id)).to be true end end context 'when SSM agent is not online' do it 'returns false' do response = double( instance_information_list: [ double(ping_status: 'ConnectionLost'), ] ) expect(ssm_client).to receive(:describe_instance_information) .with(filters: [{ key: 'InstanceIds', values: [instance_id] }]) .and_return(response) expect(ssm_manager.ssm_agent_available?(instance_id)).to be false end end context 'when instance not found in SSM' do it 'returns false' do response = double(instance_information_list: []) expect(ssm_client).to receive(:describe_instance_information) .with(filters: [{ key: 'InstanceIds', values: [instance_id] }]) .and_return(response) expect(ssm_manager.ssm_agent_available?(instance_id)).to be false end end context 'when SSM API call fails' do it 'returns false and logs warning' do expect(ssm_client).to receive(:describe_instance_information) .and_raise(Aws::SSM::Errors::ServiceError.new(nil, 'API Error')) expect(logger).to receive(:warn).with(/Error checking SSM agent status/) expect(ssm_manager.ssm_agent_available?(instance_id)).to be false end end end describe '#session_manager_plugin_installed?' do context 'when plugin is installed' do it 'returns true' do status_double = double(success?: true) allow(Open3).to receive(:capture2e).with('session-manager-plugin', '--version').and_return(["1.2.3\n", status_double]) expect(ssm_manager.session_manager_plugin_installed?).to be true end end context 'when plugin is not installed' do it 'returns false and logs warning' do status_double = double(success?: false) allow(Open3).to receive(:capture2e).with('session-manager-plugin', '--version').and_return(['', status_double]) expect(logger).to receive(:warn).with(/Session Manager plugin is not installed/) expect(ssm_manager.session_manager_plugin_installed?).to be false end end end end ================================================ FILE: spec/kitchen/driver/aws/standard_platform_spec.rb ================================================ # # Author:: Tyler Ball () # # Copyright:: 2015-2018, Fletcher Nichol # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "kitchen/driver/aws/standard_platform" require "kitchen/driver/ec2" describe Kitchen::Driver::Aws::StandardPlatform do let(:klass) { Kitchen::Driver::Aws::StandardPlatform } describe "parse_platform_string" do let(:platform_string) { "ubuntu-1604-x86_64" } it "successfully parses platform, version and architecture" do expect(klass.parse_platform_string(platform_string)).to eq(%w{ubuntu 1604 x86_64}) end context "when there is just a platform" do let(:platform_string) { "ubuntu" } it "successfully parses platform" do expect(klass.parse_platform_string(platform_string)).to eq(["ubuntu", nil, nil]) end end context "when there is just platform and version" do let(:platform_string) { "ubuntu-1604" } it "successfully parses platform and version" do expect(klass.parse_platform_string(platform_string)).to eq(["ubuntu", "1604", nil]) end end context "when there is an unknown architecture" do let(:platform_string) { "ubuntu-1604-powerpc" } it "successfully parses platform and includes architecture in version" do expect(klass.parse_platform_string(platform_string)).to eq(["ubuntu", "1604-powerpc", nil]) end end end describe "from_platform_string" do let(:driver) { instance_double(Kitchen::Driver::Ec2) } let(:platform_string) { "ubuntu-1604-x86_64" } it "returns an ubuntu StandardPlatform" do expect(klass.from_platform_string(driver, platform_string)).to be_instance_of(klass::Ubuntu) end end describe "#sort_images" do let(:img1) do instance_double(Aws::EC2::Image, creation_date: "1543439623", architecture: "amd64", block_device_mappings: [], root_device_type: "other", virtualization_type: "other", name: "ubuntu") end let(:img2) do instance_double(Aws::EC2::Image, creation_date: "1543439623", architecture: "x86_64", block_device_mappings: [], root_device_type: "other", virtualization_type: "other", name: "ubuntu") end let(:img3) do instance_double(Aws::EC2::Image, creation_date: "1543439623", architecture: "x86_64", block_device_mappings: [], root_device_type: "ebs", virtualization_type: "other", name: "ubuntu") end let(:img4) do instance_double(Aws::EC2::Image, creation_date: "1543439623", architecture: "x86_64", block_device_mappings: [], root_device_type: "ebs", virtualization_type: "hvm", name: "ubuntu") end let(:images) { [img1, img2, img3, img4] } let(:sorted_images) { [img4, img3, img2, img1] } let(:standard_platform) { klass.new(nil, nil, nil, nil) } it "correctly sorts the images" do expect(standard_platform.send(:sort_images, images)).to eq(sorted_images) end end end ================================================ FILE: spec/kitchen/driver/ec2_spec.rb ================================================ # # Author:: Tyler Ball () # # Copyright:: 2015-2018, Fletcher Nichol # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "kitchen/driver/ec2" require "kitchen/provisioner/dummy" require "kitchen/transport/dummy" require "kitchen/verifier/dummy" describe Kitchen::Driver::Ec2 do let(:logged_output) { StringIO.new } let(:logger) { Logger.new(logged_output) } let(:config) do { aws_ssh_key_id: "key", image_id: "ami-1234567", block_duration_minutes: 60, subnet_id: "subnet-1234", security_group_ids: ["sg-56789"], } end let(:platform) { Kitchen::Platform.new(name: "fooos-99") } let(:transport) { Kitchen::Transport::Dummy.new } let(:provisioner) { Kitchen::Provisioner::Dummy.new } let(:generator) { instance_double(Kitchen::Driver::Aws::InstanceGenerator) } # There is too much name overlap I let creep in - my `client` is actually # a wrapper around the actual ec2 client let(:actual_client) { double("actual ec2 client") } let(:client) { double(Kitchen::Driver::Aws::Client, client: actual_client) } let(:server) { double("aws server object") } let(:state) { {} } let(:driver) { Kitchen::Driver::Ec2.new(config) } let(:instance) do instance_double( Kitchen::Instance, logger: logger, transport: transport, provisioner: provisioner, platform: platform, to_str: "str" ) end before do allow(Kitchen::Driver::Aws::InstanceGenerator).to receive(:new).and_return(generator) allow(Kitchen::Driver::Aws::Client).to receive(:new).and_return(client) allow(driver).to receive(:windows_os?).and_return(false) allow(driver).to receive(:instance).and_return(instance) end it "driver api_version is 2" do expect(driver.diagnose_plugin[:api_version]).to eq(2) end it "plugin_version is set to Kitchen::Vagrant::VERSION" do expect(driver.diagnose_plugin[:version]).to eq( Kitchen::Driver::EC2_VERSION ) end describe "default_config" do context "Windows" do let(:resource) { instance_double(Aws::EC2::Resource, image: image) } before do allow(driver).to receive(:windows_os?).and_return(true) allow(client).to receive(:resource).and_return(resource) allow(instance).to receive(:name).and_return("instance_name") end context "Windows 2016" do let(:image) do FakeImage.new(name: "Windows_Server-2016-English-Full-Base-2017.01.11") end it "sets :user_data to something" do expect(driver[:user_data]).to include("$logfile='C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Log\\kitchen-ec2.log'") end end context "Windows 2019" do let(:image) do FakeImage.new(name: "Windows_Server-2019-English-Full-Base-2019.06.12") end it "sets :user_data to something" do expect(driver[:user_data]).to include("$logfile='C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Log\\kitchen-ec2.log'") end end context "Windows 2012R2" do let(:image) do FakeImage.new(name: "Windows_Server-2012-R2_RTM-English-64Bit-Base-2017.01.11") end it "sets :user_data to something" do expect(driver[:user_data]).to include("$logfile='C:\\Program Files\\Amazon\\Ec2ConfigService\\Logs\\kitchen-ec2.log'") end end end end describe "#hostname" do let(:public_dns_name) { nil } let(:private_dns_name) { nil } let(:public_ip_address) { nil } let(:private_ip_address) { nil } let(:id) { nil } let(:server) do double("server", public_dns_name: public_dns_name, private_dns_name: private_dns_name, public_ip_address: public_ip_address, private_ip_address: private_ip_address, id: id) end it "returns nil if all sources are nil" do expect(driver.hostname(server)).to eq(nil) end it "raises an error if provided an unknown interface" do expect { driver.hostname(server, "foobar") }.to raise_error(Kitchen::UserError) end shared_examples "an interface type provided" do it "returns public_dns_name when requested" do expect(driver.hostname(server, "dns")).to eq(public_dns_name) end it "returns public_ip_address when requested" do expect(driver.hostname(server, "public")).to eq(public_ip_address) end it "returns private_ip_address when requested" do expect(driver.hostname(server, "private")).to eq(private_ip_address) end it "returns private_dns_name when requested" do expect(driver.hostname(server, "private_dns")).to eq(private_dns_name) end it "returns id when requested" do expect(driver.hostname(server, "id")).to eq(id) end end context "private_dns_name is populated" do let(:private_dns_name) { "private_dns_name" } it "returns the private_dns_name" do expect(driver.hostname(server)).to eq(private_dns_name) end include_examples "an interface type provided" end context "private_ip_address is populated" do let(:private_dns_name) { "private_dns_name" } let(:private_ip_address) { "10.0.0.1" } it "returns the private_ip_address" do expect(driver.hostname(server)).to eq(private_ip_address) end include_examples "an interface type provided" end context "public_ip_address is populated" do let(:private_dns_name) { "private_dns_name" } let(:private_ip_address) { "10.0.0.1" } let(:public_ip_address) { "127.0.0.1" } it "returns the public_ip_address" do expect(driver.hostname(server)).to eq(public_ip_address) end include_examples "an interface type provided" end context "public_dns_name is populated" do let(:private_dns_name) { "private_dns_name" } let(:private_ip_address) { "10.0.0.1" } let(:public_ip_address) { "127.0.0.1" } let(:public_dns_name) { "public_dns_name" } it "returns the public_dns_name" do expect(driver.hostname(server)).to eq(public_dns_name) end include_examples "an interface type provided" end context "public_dns_name returns as empty string" do let(:public_dns_name) { "" } it "returns nil" do expect(driver.hostname(server)).to eq(nil) end context "and private_ip_address is populated" do let(:private_ip_address) { "10.0.0.1" } it "returns the private_ip_address" do expect(driver.hostname(server)).to eq(private_ip_address) end context "and private_dns_name is populated" do let(:private_dns_name) { "private_dns_name" } it "returns the private_ip_address" do expect(driver.hostname(server)).to eq(private_ip_address) end end end end end describe "#submit_server" do before do expect(driver).to receive(:instance).at_least(:once).and_return(instance) end it "submits the server request" do expect(generator).to receive(:ec2_instance_data).and_return({}) expect(client).to receive(:create_instance) driver.submit_server end end describe "submit_server with terminate shutdown behaviour" do before do config[:instance_initiated_shutdown_behavior] = "terminate" expect(driver).to receive(:instance).at_least(:once).and_return(instance) end it "submits the server request" do expect(generator).to receive(:ec2_instance_data).and_return( { instance_initiated_shutdown_behavior: "terminate" } ) expect(client).to receive(:create_instance).with( { instance_initiated_shutdown_behavior: "terminate" } ) driver.submit_server end end describe "#submit_spot" do before do expect(driver).to receive(:instance).at_least(:once).and_return(instance) end it "submits the server request" do expect(generator).to receive(:ec2_instance_data).and_return({}) expect(client).to receive(:create_instance).with({ instance_market_options: { market_type: "spot", spot_options: { block_duration_minutes: 60, }, }, }).and_return(server) driver.submit_spot end end describe "#wait_until_ready" do let(:hostname) { "0.0.0.0" } let(:msg) { "to become ready" } let(:aws_instance) { double("aws instance") } before do config[:interface] = :i expect(driver).to receive(:wait_with_destroy).with(server, state, msg).and_yield(aws_instance) expect(driver).to receive(:hostname).with(aws_instance, :i).and_return(hostname) end after do expect(state[:hostname]).to eq(hostname) end it "first checks instance existence" do expect(aws_instance).to receive(:exists?).and_return(false) expect(driver.wait_until_ready(server, state)).to eq(false) end it "second checks instance state" do expect(aws_instance).to receive(:exists?).and_return(true) expect(aws_instance).to receive_message_chain("state.name").and_return("nope") expect(driver.wait_until_ready(server, state)).to eq(false) end it "third checks hostname" do expect(aws_instance).to receive(:exists?).and_return(true) expect(aws_instance).to receive_message_chain("state.name").and_return("running") expect(driver.wait_until_ready(server, state)).to eq(false) end context "when it exists, has a valid state and a valid hostname" do let(:hostname) { "host" } it "returns true" do expect(aws_instance).to receive(:exists?).and_return(true) expect(aws_instance).to receive_message_chain("state.name").and_return("running") expect(driver.wait_until_ready(server, state)).to eq(true) end end context "when windows instance" do let(:hostname) { "windows" } before do expect(aws_instance).to receive(:exists?).and_return(true) expect(aws_instance).to receive_message_chain("state.name").and_return("running") expect(driver).to receive(:windows_os?).and_return(true) end context "does define a username/password" do before do expect(transport).to receive(:[]).with(:username).and_return("foo") end context "console output is ready" do it "returns true" do # base64 encoded `Windows is Ready to use` expect(server).to receive_message_chain("console_output.output").and_return("V2luZG93cyBpcyBSZWFkeSB0byB1c2U=") expect(driver.wait_until_ready(server, state)).to eq(true) end end context "console output is not ready" do it "returns false" do expect(server).to receive_message_chain("console_output.output").and_return("") expect(driver.wait_until_ready(server, state)).to eq(false) end end end context "does not define a username/password" do it "returns true" do expect(transport).to receive(:[]).with(:username).and_return("administrator") expect(transport).to receive(:[]).with(:password).and_return(nil) expect(driver).to receive(:fetch_windows_admin_password).with(server, state) expect(driver.wait_until_ready(server, state)).to eq(true) end end end end describe "#fetch_windows_admin_password" do let(:msg) { "to fetch windows admin password" } let(:aws_instance) { double("aws instance") } let(:server_id) { "server_id" } let(:encrypted_password) { "alksdofw" } let(:data) { double("data", password_data: encrypted_password) } let(:password) { "password" } let(:transport) { { ssh_key: "foo" } } before do state[:server_id] = server_id expect(driver).to receive(:wait_with_destroy).with(server, state, msg).and_yield(aws_instance) end after do expect(state[:password]).to eq(password) end it "fetches and decrypts the windows password" do expect(server).to receive_message_chain("client.get_password_data").with( instance_id: server_id ).and_return(data) expect(server).to receive(:decrypt_windows_password) .with(File.expand_path("foo")) .and_return(password) driver.fetch_windows_admin_password(server, state) end end describe "#wait_with_destroy" do let(:tries) { 111 } let(:sleep) { 222 } let(:msg) { "msg" } given_block = lambda { ; } before do config[:retryable_sleep] = sleep config[:retryable_tries] = tries end it "calls wait and exits successfully if there is no error" do expect(server).to receive(:wait_until) do |args, &block| expect(args[:max_attempts]).to eq(tries) expect(args[:delay]).to eq(sleep) expect(block).to eq(given_block) expect(driver).to receive(:info).with(/#{msg}/) args[:before_attempt].call(0) end driver.wait_with_destroy(server, state, msg, &given_block) end it "attempts to destroy the instance if the waiter fails" do expect(server).to receive(:wait_until).and_raise(Aws::Waiters::Errors::WaiterFailed) expect(driver).to receive(:destroy).with(state) expect(driver).to receive(:error).with(/#{msg}/) expect do driver.wait_with_destroy(server, state, msg, &given_block) end.to raise_error(Aws::Waiters::Errors::WaiterFailed) end end describe "#create_key" do context "creates a key pair via the ec2 API, saves the generated key locally" do before do config[:kitchen_root] = "/kitchen" config.delete(:aws_ssh_key_id) allow(instance).to receive(:name).and_return("instance_name") expect(actual_client).to receive(:create_key_pair).with( key_name: /kitchen-/, key_type: "rsa", tag_specifications: [{ resource_type: "key-pair", tags: [{ key: "created-by", value: "test-kitchen" }] }] ).and_return(double(key_name: "expected-key-name", key_material: "RSA PRIVATE KEY")) fake_file = double allow(File).to receive(:open).and_call_original expect(File).to receive(:open).with("/kitchen/.kitchen/instance_name.pem", kind_of(Numeric), kind_of(Numeric)).and_yield(fake_file) expect(fake_file).to receive(:write).with("RSA PRIVATE KEY") end it "generates a temporary SSH key pair for the instance" do driver.send(:create_key, state) expect(state[:auto_key_id]).to eq("expected-key-name") expect(state[:ssh_key]).to eq("/kitchen/.kitchen/instance_name.pem") end end end describe "#create" do let(:server) { double("aws server object", id: id, image_id: "ami-3f807145") } let(:id) { "i-12345" } it "returns if the instance is already created" do state[:server_id] = id expect(driver.create(state)).to eq(nil) end image_data = Aws::EC2::Types::Image.new(root_device_type: "ebs") ec2_stub = Aws::EC2::Types::DescribeImagesResult.new ec2_stub.images = [image_data] shared_examples "common create" do it "successfully creates and tags the instance" do expect(server).to receive(:wait_until_exists) expect(driver).to receive(:update_username) expect(driver).to receive(:wait_until_ready).with(server, state) expect(transport).to receive_message_chain("connection.wait_until_ready") driver.create(state) expect(state[:server_id]).to eq(id) end end context "chef provisioner" do let(:provisioner) { double("chef provisioner", name: "chef_solo") } before do expect(driver).to receive(:create_ec2_json).with(state) expect(driver).to receive(:submit_server).and_return(server) end include_examples "common create" end context "non-windows on-demand instance" do before do expect(driver).to receive(:submit_server).and_return(server) end include_examples "common create" end context "config is for a spot instance" do before do config[:spot_price] = 1 end context "price is numeric" do before do expect(driver).to receive(:submit_spots).and_return(server) end include_examples "common create" end context "price is on-demand" do before do config[:spot_price] = "on-demand" expect(driver).to receive(:submit_spots).and_return(server) end include_examples "common create" end context "instance_type is an array" do before do config[:instance_type] = %w{t1 t2} expect(driver).to receive(:submit_spot).and_return(server) end include_examples "common create" context "subnets is also an array" do before do config[:subnet_id] = %w{t1 t2} end include_examples "common create" end end end context "instance is a windows machine" do before do expect(driver).to receive(:submit_server).and_return(server) end include_examples "common create" end context "instance is not a standard platform" do let(:state) { {} } before do expect(driver).to receive(:actual_platform).and_return(nil) end it "doesn't set the state username" do driver.update_username(state) expect(state).to eq({}) end end context "with no security group specified" do before do config.delete(:security_group_ids) expect(driver).to receive(:submit_server).and_return(server) allow(instance).to receive(:name).and_return("instance_name") end context "with a subnet configured" do before do expect(actual_client).to receive(:describe_subnets).with(filters: [{ name: "subnet-id", values: ["subnet-1234"] }]).and_return(double(subnets: [double(vpc_id: "vpc-1")])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, vpc_id: "vpc-1", tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, ]) end include_examples "common create" end context "with a subnet filter configured" do before do config.delete(:subnet_id) config[:subnet_filter] = { tag: "foo", value: "bar", } expect(actual_client).to receive(:describe_subnets).with({ filters: [{ name: "tag:foo", values: ["bar"] }] }).and_return(double(subnets: [double(vpc_id: "vpc-1")])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, vpc_id: "vpc-1", tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, ]) end include_examples "common create" end context "with multiple subnet filters configured" do before do config.delete(:subnet_id) config[:subnet_filter] = [{ tag: "foo", value: "bar", }, { tag: "hello", value: "world", }] expect(actual_client).to receive(:describe_subnets).with({ filters: [{ name: "tag:foo", values: ["bar"] }, { name: "tag:hello", values: ["world"] }] }).and_return(double(subnets: [double(vpc_id: "vpc-1")])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, vpc_id: "vpc-1", tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, ]) end include_examples "common create" end context "with an ip address configured as a string" do before do config[:security_group_cidr_ip] = "1.2.3.4/32" expect(actual_client).to receive(:describe_subnets).with(filters: [{ name: "subnet-id", values: ["subnet-1234"] }]).and_return(double(subnets: [double(vpc_id: "vpc-1")])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, vpc_id: "vpc-1", tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "1.2.3.4/32" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "1.2.3.4/32" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "1.2.3.4/32" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "1.2.3.4/32" }] }, ]) end include_examples "common create" end context "with an ip address configured as an array" do before do config[:security_group_cidr_ip] = ["10.0.0.0/22"] expect(actual_client).to receive(:describe_subnets).with(filters: [{ name: "subnet-id", values: ["subnet-1234"] }]).and_return(double(subnets: [double(vpc_id: "vpc-1")])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, vpc_id: "vpc-1", tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }] }, ]) end include_examples "common create" end context "with multiple ip addresses configured as an array" do before do config[:security_group_cidr_ip] = ["10.0.0.0/22", "172.16.0.0/24"] expect(actual_client).to receive(:describe_subnets).with(filters: [{ name: "subnet-id", values: ["subnet-1234"] }]).and_return(double(subnets: [double(vpc_id: "vpc-1")])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, vpc_id: "vpc-1", tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }, { cidr_ip: "172.16.0.0/24" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }, { cidr_ip: "172.16.0.0/24" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }, { cidr_ip: "172.16.0.0/24" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "10.0.0.0/22" }, { cidr_ip: "172.16.0.0/24" }] }, ]) end include_examples "common create" end context "with a default VPC" do before do config.delete(:subnet_id) expect(actual_client).to receive(:describe_vpcs).with(filters: [{ name: "isDefault", values: ["true"] }]).and_return(double(vpcs: [double(vpc_id: "vpc-1")])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, vpc_id: "vpc-1", tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, ]) end include_examples "common create" end context "without a default VPC" do before do config.delete(:subnet_id) expect(actual_client).to receive(:describe_vpcs).with(filters: [{ name: "isDefault", values: ["true"] }]).and_return(double(vpcs: [])) expect(actual_client).to receive(:create_security_group).with({ group_name: /kitchen-/, description: /Test Kitchen for/, tag_specifications: [{ resource_type: "security-group", tags: [{ key: "created-by", value: "test-kitchen" }] }], }).and_return(double(group_id: "sg-9876")) expect(actual_client).to receive(:authorize_security_group_ingress).with(group_id: "sg-9876", ip_permissions: [ { ip_protocol: "tcp", from_port: 22, to_port: 22, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 3389, to_port: 3389, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5985, to_port: 5985, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, { ip_protocol: "tcp", from_port: 5986, to_port: 5986, ip_ranges: [{ cidr_ip: "0.0.0.0/0" }] }, ]) end include_examples "common create" end end context "with no security group but filter specified" do before do config.delete(:security_group_ids) config[:security_group_filter] = { tag: "SomeTag", value: "SomeValue" } expect(driver).not_to receive(:create_security_group) expect(driver).to receive(:submit_server).and_return(server) allow(instance).to receive(:name).and_return("instance_name") end include_examples "common create" end context "and AWS SSH keys" do before do allow(driver).to receive(:submit_server).and_return(server) allow(instance).to receive(:name).and_return("instance_name") end context "with no AWS-managed ssh key pair configured, creates a key pair to use" do before do config[:aws_ssh_key_id] = nil expect(driver).to receive(:create_key) state[:auto_key_id] = "autogenerated_by_create_key" end after do expect(config[:aws_ssh_key_id]).to eq("autogenerated_by_create_key") end include_examples "common create" end context "with AWS-managed ssh key pair disabled, does not create a key pair or pass a key id" do before do config[:aws_ssh_key_id] = "_disable" expect(driver).to_not receive(:create_key) end after do expect(config[:aws_ssh_key_id]).to be_nil end include_examples "common create" end context "with AWS ssh key pair set, uses set key and does not create a key pair" do before do config[:aws_ssh_key_id] = "use_this_key_please" expect(driver).to_not receive(:create_key) end after do expect(config[:aws_ssh_key_id]).to eq("use_this_key_please") end include_examples "common create" end end end describe "#destroy" do context "when state[:server_id] is nil" do it "returns nil" do expect(driver.destroy(state)).to eq(nil) end end context "when state has a normal server_id" do let(:state) { { server_id: "id", hostname: "name" } } context "the server is already destroyed" do it "does nothing" do expect(client).to receive(:get_instance).with("id").and_return nil driver.destroy(state) expect(state).to eq({}) end end it "destroys the server" do expect(client).to receive(:get_instance).with("id").and_return(server) expect(instance).to receive_message_chain("transport.connection.close") expect(server).to receive(:terminate) driver.destroy(state) expect(state).to eq({}) end end context "when the state has an automatic security group" do let(:state) { { auto_security_group_id: "sg-asdf" } } it "destroys the security group" do expect(actual_client).to receive(:delete_security_group).with(group_id: "sg-asdf") driver.destroy(state) expect(state).to eq({}) end end context "when the state has an automatic key pair" do let(:state) { { auto_key_id: "kitchen-asdf" } } it "destroys the key pair" do config[:kitchen_root] = "/kitchen" allow(instance).to receive(:name).and_return("instance_name") expect(actual_client).to receive(:delete_key_pair).with(key_name: "kitchen-asdf") expect(File).to receive(:unlink).with("/kitchen/.kitchen/instance_name.pem") driver.destroy(state) expect(state).to eq({}) end end end describe "Instance Connect functionality" do let(:state) { { server_id: "i-12345", ssh_key: "/path/to/key.pem", username: "ec2-user" } } describe "#instance_connect_configure_ssh_proxy_command" do context "with instance_connect_endpoint_id configured" do let(:config) do { use_instance_connect: true, instance_connect_endpoint_id: "eice-12345", instance_connect_max_tunnel_duration: 3600, shared_credentials_profile: "my-profile", region: "us-east-1" } end it "sets up SSH proxy command with all parameters" do driver.send(:instance_connect_configure_ssh_proxy_command, state) expected_command = "aws ec2-instance-connect open-tunnel --instance-id i-12345 " \ "--instance-connect-endpoint-id eice-12345 --max-tunnel-duration 3600 " \ "--profile my-profile --region us-east-1" expect(state[:ssh_proxy_command]).to eq(expected_command) end it "stores instance connect config in state" do driver.send(:instance_connect_configure_ssh_proxy_command, state) expect(state[:instance_connect_config]).to eq({ server_id: "i-12345", username: "ec2-user", region: "us-east-1", profile: "my-profile", tunnel_mode: true }) end end context "with minimal configuration" do let(:config) do { use_instance_connect: true, region: "us-west-2" } end it "sets up SSH proxy command with minimal parameters" do driver.send(:instance_connect_configure_ssh_proxy_command, state) expected_command = "aws ec2-instance-connect open-tunnel --instance-id i-12345 --max-tunnel-duration 3600 --region us-west-2" expect(state[:ssh_proxy_command]).to eq(expected_command) end end end describe "#instance_connect_refresh_key" do let(:config) do { use_instance_connect: true, region: "us-east-1", shared_credentials_profile: "my-profile" } end before do allow(driver).to receive(:instance_connect_extract_public_key).with("/path/to/key.pem").and_return("ssh-rsa AAAAB3... test-key") end it "executes aws ec2-instance-connect send-ssh-public-key command" do expected_command = "aws ec2-instance-connect send-ssh-public-key " \ "--instance-id i-12345 --instance-os-user ec2-user " \ "--ssh-public-key ssh-rsa\\ AAAAB3...\\ test-key " \ "--region us-east-1 --profile my-profile" expect(driver).to receive(:`).with(expected_command + " 2>&1").and_return("") # Stub $? by allowing the actual command to succeed allow(driver).to receive(:warn) driver.send(:instance_connect_refresh_key, state) end it "handles command failure gracefully" do allow(driver).to receive(:`).and_return("Error: Something went wrong") expect(driver).to receive(:warn).with("[AWS EC2 Instance Connect] Failed to refresh SSH key: Error: Something went wrong") allow(driver).to receive(:`) do |cmd| # Simulate command failure by setting $? to failed status `false` "Error: Something went wrong" end driver.send(:instance_connect_refresh_key, state) end it "returns early if no key path is provided" do state.delete(:ssh_key) allow(instance.transport).to receive(:[]).with(:ssh_key).and_return(nil) expect(driver).not_to receive(:instance_connect_extract_public_key) expect(driver).not_to receive(:`) driver.send(:instance_connect_refresh_key, state) end end describe "#instance_connect_extract_public_key" do context "when .pub file exists" do it "reads the public key from .pub file" do allow(File).to receive(:exist?).with("/path/to/key.pem.pub").and_return(true) allow(File).to receive(:read).with("/path/to/key.pem.pub").and_return("ssh-rsa AAAAB3... test-key\n") result = driver.send(:instance_connect_extract_public_key, "/path/to/key.pem") expect(result).to eq("ssh-rsa AAAAB3... test-key") end end context "when .pub file does not exist" do before do allow(File).to receive(:exist?).with("/path/to/key.pem.pub").and_return(false) allow(File).to receive(:read).with("/path/to/key.pem").and_return("-----BEGIN RSA PRIVATE KEY-----\n...") end it "extracts public key from private key using SSHKey" do ssh_key_mock = double("SSHKey") allow(SSHKey).to receive(:new).with("-----BEGIN RSA PRIVATE KEY-----\n...").and_return(ssh_key_mock) allow(ssh_key_mock).to receive(:ssh_public_key).and_return("ssh-rsa AAAAB3... generated-key") result = driver.send(:instance_connect_extract_public_key, "/path/to/key.pem") expect(result).to eq("ssh-rsa AAAAB3... generated-key") end it "raises error if SSHKey fails" do allow(SSHKey).to receive(:new).and_raise(StandardError.new("Invalid key format")) expect { driver.send(:instance_connect_extract_public_key, "/path/to/key.pem") } .to raise_error("Unable to extract public key from /path/to/key.pem: Invalid key format") end end end describe "#instance_connect_setup_ready" do context "when endpoint is available (tunnel mode)" do let(:config) do { use_instance_connect: true, instance_connect_endpoint_id: "eice-12345", region: "us-east-1" } end before do allow(driver).to receive(:instance_connect_endpoint_available?).with(state).and_return(true) end it "configures SSH proxy command and refreshes key" do expect(driver).to receive(:instance_connect_configure_ssh_proxy_command).with(state) expect(driver).to receive(:instance_connect_refresh_key).with(state) expect(driver).to receive(:info).with("[AWS EC2 Instance Connect] Using tunnel mode - Instance Connect endpoint available") driver.send(:instance_connect_setup_ready, state) end context "when ssh_proxy_command is already set" do before do state[:ssh_proxy_command] = "existing-command" end it "skips SSH proxy command configuration but still refreshes key" do expect(driver).not_to receive(:instance_connect_configure_ssh_proxy_command) expect(driver).to receive(:instance_connect_refresh_key).with(state) expect(driver).to receive(:info).with("[AWS EC2 Instance Connect] Using tunnel mode - Instance Connect endpoint available") driver.send(:instance_connect_setup_ready, state) end end end context "when endpoint is not available (direct SSH mode)" do let(:config) do { use_instance_connect: true, region: "us-east-1" } end before do allow(driver).to receive(:instance_connect_endpoint_available?).with(state).and_return(false) end it "configures direct SSH and refreshes key" do expect(driver).to receive(:instance_connect_configure_direct_ssh).with(state) expect(driver).to receive(:instance_connect_refresh_key).with(state) expect(driver).to receive(:info).with("[AWS EC2 Instance Connect] Using direct SSH mode - no Instance Connect endpoint") driver.send(:instance_connect_setup_ready, state) end end end describe "#instance_connect_endpoint_available?" do let(:vpc_id) { "vpc-12345" } let(:state) { { server_id: "i-12345" } } before do allow(driver).to receive(:get_vpc_id_for_instance).with(state).and_return(vpc_id) end context "when instance_connect_endpoint_id is explicitly configured" do let(:config) { { instance_connect_endpoint_id: "eice-12345" } } it "returns true without checking VPC endpoints" do expect(actual_client).not_to receive(:describe_instance_connect_endpoints) result = driver.send(:instance_connect_endpoint_available?, state) expect(result).to be true end end context "when no explicit endpoint_id is configured" do let(:config) { {} } context "and VPC has active endpoints" do let(:endpoints) { [double("endpoint", state: "create-complete")] } before do allow(actual_client).to receive(:describe_instance_connect_endpoints).with( filters: [ { name: "vpc-id", values: [vpc_id] }, { name: "state", values: ["create-complete"] } ] ).and_return(double(instance_connect_endpoints: endpoints)) end it "returns true" do result = driver.send(:instance_connect_endpoint_available?, state) expect(result).to be true end end context "and VPC has no active endpoints" do before do allow(actual_client).to receive(:describe_instance_connect_endpoints).with( filters: [ { name: "vpc-id", values: [vpc_id] }, { name: "state", values: ["create-complete"] } ] ).and_return(double(instance_connect_endpoints: [])) end it "returns false" do result = driver.send(:instance_connect_endpoint_available?, state) expect(result).to be false end end context "and endpoint checking fails" do before do allow(actual_client).to receive(:describe_instance_connect_endpoints) .and_raise(Aws::EC2::Errors::InvalidAction.new("context", "Not supported in this region")) end it "returns false and logs debug message" do expect(driver).to receive(:debug).with("[AWS EC2 Instance Connect] Cannot check for endpoints: Not supported in this region") result = driver.send(:instance_connect_endpoint_available?, state) expect(result).to be false end end context "and no VPC ID is available" do before do allow(driver).to receive(:get_vpc_id_for_instance).with(state).and_return(nil) end it "returns false" do expect(actual_client).not_to receive(:describe_instance_connect_endpoints) result = driver.send(:instance_connect_endpoint_available?, state) expect(result).to be false end end end end describe "#get_vpc_id_for_instance" do let(:state) { { server_id: "i-12345" } } let(:instance_info) { double("instance", vpc_id: "vpc-12345") } let(:reservation) { double("reservation", instances: [instance_info]) } context "when instance exists" do before do allow(actual_client).to receive(:describe_instances).with(instance_ids: ["i-12345"]) .and_return(double(reservations: [reservation])) end it "returns the VPC ID" do result = driver.send(:get_vpc_id_for_instance, state) expect(result).to eq("vpc-12345") end end context "when instance does not exist" do before do allow(actual_client).to receive(:describe_instances).with(instance_ids: ["i-12345"]) .and_return(double(reservations: [])) end it "returns nil" do result = driver.send(:get_vpc_id_for_instance, state) expect(result).to be_nil end end context "when server_id is not present" do let(:state) { {} } it "returns nil" do expect(actual_client).not_to receive(:describe_instances) result = driver.send(:get_vpc_id_for_instance, state) expect(result).to be_nil end end context "when API call fails" do before do allow(actual_client).to receive(:describe_instances) .and_raise(StandardError.new("API Error")) end it "returns nil and logs debug message" do expect(driver).to receive(:debug).with("[AWS EC2 Instance Connect] Error getting VPC ID for instance: API Error") result = driver.send(:get_vpc_id_for_instance, state) expect(result).to be_nil end end end describe "#instance_connect_configure_direct_ssh" do let(:state) { { server_id: "i-12345", username: "ec2-user" } } let(:server) { double("server", public_dns_name: "ec2-1-2-3-4.compute-1.amazonaws.com") } let(:config) do { region: "us-east-1", shared_credentials_profile: "my-profile" } end before do allow(client).to receive(:get_instance).with("i-12345").and_return(server) end context "when public DNS is available" do it "sets hostname to public DNS and stores config" do expect(driver).to receive(:info).with("[AWS EC2 Instance Connect] Configuring direct SSH to ec2-1-2-3-4.compute-1.amazonaws.com") driver.send(:instance_connect_configure_direct_ssh, state) expect(state[:hostname]).to eq("ec2-1-2-3-4.compute-1.amazonaws.com") expect(state[:instance_connect_config]).to eq({ server_id: "i-12345", username: "ec2-user", region: "us-east-1", profile: "my-profile", direct_ssh: true, hostname: "ec2-1-2-3-4.compute-1.amazonaws.com" }) end end context "when public DNS is not available" do let(:server) { double("server", public_dns_name: nil) } it "warns and does not change hostname" do original_hostname = state[:hostname] expect(driver).to receive(:warn).with("[AWS EC2 Instance Connect] No public DNS available for direct SSH, falling back to existing hostname") driver.send(:instance_connect_configure_direct_ssh, state) expect(state[:hostname]).to eq(original_hostname) end end context "when public DNS is empty string" do let(:server) { double("server", public_dns_name: "") } it "warns and does not change hostname" do original_hostname = state[:hostname] expect(driver).to receive(:warn).with("[AWS EC2 Instance Connect] No public DNS available for direct SSH, falling back to existing hostname") driver.send(:instance_connect_configure_direct_ssh, state) expect(state[:hostname]).to eq(original_hostname) end end end describe "integration with create method" do let(:server) { double("aws server object", id: "i-12345") } let(:create_state) { { ssh_key: "/path/to/key.pem", username: "ec2-user" } } let(:config) do { use_instance_connect: true, instance_connect_endpoint_id: "eice-12345", region: "us-east-1", aws_ssh_key_id: "test-key", image_id: "ami-12345", security_group_ids: ["sg-12345"] } end before do allow(driver).to receive(:update_username) allow(driver).to receive(:submit_server).and_return(server) allow(server).to receive(:wait_until_exists) allow(driver).to receive(:attach_network_interface) allow(driver).to receive(:create_ec2_json) allow(driver).to receive(:debug) allow(driver).to receive(:info) # Stub methods that might cause early exits allow(driver).to receive(:create_security_group) allow(driver).to receive(:create_key) allow(driver).to receive(:host_available?).and_return(true) # Stub wait_until_ready and the Retryable wrapper allow(driver).to receive(:wait_until_ready) do |_, state| state[:hostname] = "test-hostname" true end # Allow the Retryable block to execute normally allow(Retryable).to receive(:retryable) do |options, &block| block.call(1, nil) end # Mock the transport connection wait_until_ready call connection_double = double("connection", wait_until_ready: true) allow(instance.transport).to receive(:connection).with(any_args).and_return(connection_double) end it "calls instance_connect_setup_ready when use_instance_connect is true" do expect(driver).to receive(:instance_connect_setup_ready).with(hash_including(server_id: "i-12345")) driver.create(create_state) end it "does not call instance_connect_setup_ready when use_instance_connect is false" do config[:use_instance_connect] = false expect(driver).not_to receive(:instance_connect_setup_ready) driver.create(create_state) end end end describe "SSM Session Manager functionality" do describe "integration with create method" do let(:ssm_manager) { instance_double(Kitchen::Driver::Aws::SsmSessionManager) } let(:create_state) { {} } let(:config) do { use_ssm_session_manager: true, region: "us-east-1", aws_ssh_key_id: "test-key", image_id: "ami-12345", security_group_ids: ["sg-12345"], } end before do allow(driver).to receive(:update_username) allow(driver).to receive(:submit_server).and_return(server) allow(server).to receive(:wait_until_exists) allow(server).to receive(:id).and_return("i-12345") allow(driver).to receive(:attach_network_interface) allow(driver).to receive(:create_ec2_json) allow(driver).to receive(:debug) allow(driver).to receive(:info) allow(driver).to receive(:create_security_group) allow(driver).to receive(:create_key) allow(driver).to receive(:host_available?).and_return(true) allow(driver).to receive(:ssm_session_manager).and_return(ssm_manager) allow(driver).to receive(:wait_until_ready) do |_, state| state[:hostname] = "test-hostname" true end allow(Retryable).to receive(:retryable) do |_options, &block| block.call(1, nil) end connection_double = double("connection", wait_until_ready: true) allow(instance.transport).to receive(:connection).with(any_args).and_return(connection_double) end it "calls ssm_session_manager_setup_ready when use_ssm_session_manager is true" do expect(driver).to receive(:ssm_session_manager_setup_ready).with(hash_including(server_id: "i-12345")) driver.create(create_state) end it "does not call ssm_session_manager_setup_ready when use_ssm_session_manager is false" do config[:use_ssm_session_manager] = false expect(driver).not_to receive(:ssm_session_manager_setup_ready) driver.create(create_state) end end describe "#ssm_session_manager_setup_ready" do let(:state) { { server_id: "i-12345" } } let(:ssm_manager) { instance_double(Kitchen::Driver::Aws::SsmSessionManager) } before do allow(driver).to receive(:ssm_session_manager).and_return(ssm_manager) allow(driver).to receive(:info) allow(driver).to receive(:warn) allow(ssm_manager).to receive(:session_manager_plugin_installed?).and_return(true) end context "when SSM agent is available immediately" do it "does not wait" do expect(ssm_manager).to receive(:ssm_agent_available?).with("i-12345").and_return(true) expect(driver).not_to receive(:sleep) driver.send(:ssm_session_manager_setup_ready, state) end end context "when SSM agent becomes available after retries" do it "waits and succeeds" do call_count = 0 allow(ssm_manager).to receive(:ssm_agent_available?) do |_instance_id| call_count += 1 call_count > 2 end expect(driver).to receive(:sleep).twice driver.send(:ssm_session_manager_setup_ready, state) end end context "when session manager plugin is not installed" do it "warns the user" do allow(ssm_manager).to receive(:session_manager_plugin_installed?).and_return(false) allow(ssm_manager).to receive(:ssm_agent_available?).and_return(true) expect(driver).to receive(:warn).with(/Session Manager plugin not found/) driver.send(:ssm_session_manager_setup_ready, state) end end end describe "#ssm_session_manager_setup_override" do let(:state) { { server_id: "i-12345" } } let(:config) do { use_ssm_session_manager: true, region: "us-west-2", shared_credentials_profile: "my-profile", } end before do allow(driver).to receive(:info) end it "overrides transport connection method" do expect(instance.transport).to receive(:define_singleton_method).with(:connection) expect(instance.transport).to receive(:define_singleton_method).with(:ssm_session_manager_override_applied) driver.send(:ssm_session_manager_setup_override, instance) end it "sets SSH proxy command with correct parameters" do driver.send(:ssm_session_manager_setup_override, instance) # Call the overridden connection method original_method = instance.transport.method(:connection) allow(original_method).to receive(:call) instance.transport.connection(state) expect(state[:ssh_proxy_command]).to include("aws ssm start-session") expect(state[:ssh_proxy_command]).to include("--target i-12345") expect(state[:ssh_proxy_command]).to include("--region us-west-2") expect(state[:ssh_proxy_command]).to include("--profile my-profile") end it "includes document name when specified" do config[:ssm_session_manager_document_name] = "MyCustomDocument" driver.send(:ssm_session_manager_setup_override, instance) instance.transport.connection(state) expect(state[:ssh_proxy_command]).to include("--document-name MyCustomDocument") end it "does not apply override twice" do driver.send(:ssm_session_manager_setup_override, instance) expect(instance.transport).to respond_to(:ssm_session_manager_override_applied) # Second call should return early expect(instance.transport).not_to receive(:define_singleton_method) driver.send(:ssm_session_manager_setup_override, instance) end end end end ================================================ FILE: spec/spec_helper.rb ================================================ # # Author:: Fletcher Nichol () # # Copyright:: 2015-2018, Fletcher Nichol # Copyright:: 2016-2018, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "support/fake_image" RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = "doc" end # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed config.expose_dsl_globally = true end require "aws-sdk-ec2" # https://ruby.awsblog.com/post/Tx15V81MLPR8D73/Client-Response-Stubs Aws.config[:stub_responses] = true ================================================ FILE: spec/support/fake_image.rb ================================================ class FakeImage def self.next_ami @n ||= 0 @n += 1 [format("ami-%08x", @n), Time.now + @n] end def initialize(name: "foo") @id, @creation_date = FakeImage.next_ami @name = name @creation_date = @creation_date.strftime("%F %T") @architecture = :x86_64 @volume_type = "gp2" @root_device_type = "ebs" @virtualization_type = "hvm" @root_device_name = "root" @device_name = "root" end attr_reader :id, :name, :creation_date, :architecture, :volume_type, :root_device_type, :virtualization_type, :root_device_name, :device_name def block_device_mappings [self] end def ebs self end end